tomcat 连接失败Servlet错误java和MySql

kokeuurv  于 2023-01-09  发布在  Java
关注(0)|答案(1)|浏览(168)

今天我在java和mySql中使用servlet时遇到了一个问题,顺便说一句,我正在使用eclipse编写此代码。问题是当我使用servlet调用Tomcat中的DAO类时,我与数据库的连接失败,但当我使用普通类尝试使用java编译器时,连接良好,此错误仅在使用Tomcat时出现。
这是我的Servlet控制器(在此连接失败,我用Tomcat运行此)

public class ProductController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ProductController() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ProductDAO productDAO = new ProductDAO();
    RequestDispatcher dispatcher = null;
    String accion = request.getParameter("accion");
    
    if(accion == null || accion.isEmpty()) {
        dispatcher = request.getRequestDispatcher("products/index.jsp");
        List<Product> list = productDAO.getList();
        request.setAttribute("list", list);
    }
    dispatcher.forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
    }
}

这是我的DAO类

public class ProductDAO {
    public ProductDAO() {
    }

    public List<Product> getList() {
    Connection_ jdbc = new Connection();
    PreparedStatement ps;
    ResultSet rs;
    List<Product> list = new ArrayList<>();
    
    try {
            ps = jdbc.getConecction().prepareStatement("SELECT * FROM products");;
            rs = ps.executeQuery();
            while(rs.next()) {
        list.add(new Product(rs.getInt("id"), rs.getInt("stock"), rs.getDouble("price"), rs.getString("name"), rs.getString("code")));
            }
            return list;
    }catch (Exception e) {
            System.out.println("Fallo en la conexion");
            return null; 
    }
    }
}

这是错误消息
enter image description here
这是我的Try控制器

public class Controller{

    public static void main(String[] args) {
    Connection_ jdbc = new Connection();
    Statement statement;
    ResultSet rows;
    try {
            statement = jdbc.getConecction().createStatement();
            rows = statement.executeQuery("SELECT * FROM products");
            System.out.println("Registers");
            while(rows.next()) {
                System.out.println("Id "+rows.getInt("stock"));
            }
    } catch (Exception e) {
            System.out.println("Fallo en la conexion");
    }
}

这是我使用try控制器的时候
enter image description here
就像我之前说的,在这次尝试中我使用的是Eclipse的java编译器,我没有这个问题,但是,当我在这个控制器中再次使用tomcat时,我的系统出现故障,我不知道如何解决它

相关问题