java - 使用 Java Servlet/jsp 将产品添加到数据库

标签 java jsp servlets

你能帮我解决这个问题吗?我找不到发生了什么。 我正在使用 Java Servlet 和 JSP 开发一个 Web 应用程序。

当我尝试添加产品时,它在 URL 中显示: http://localhost:8080/ProductMaintenanceMdy/add?action=add&code=8768&description=mylove&price=15.55&Add+product=Submit

由于它显示了在 URL 中输入的数据,这意味着 addProduct.jsp 中的表单正在运行,但它不会将产品保存在数据库中。

您能检查一下我的servlet代码、映射代码和要添加的查询函数是否正确吗? 别无礼,我是初学者。

//添加产品的Servlet代码

else  if (action.equals("addProducts"))  // this is for action inside display  
{
    url= "/addProducts.jsp";
}
else if (action.equals("add")) //this is for add inside sddProducts
{  
    String code= request.getParameter("code");
    String description= request.getParameter("description");
    Double price=Double.parseDouble(request.getParameter("price"));

    Product p= new Product();
    p.setCode(code);
    p.setDescription(description);
    p.setPrice(price);

    ProductDB.insertProduct(p); //implemented it inside productDB.java
    url="/addProducts.jsp";

}

//添加 Web xml 映射部分

<servlet-mapping>
        <servlet-name>ProdMaintAppServlet</servlet-name>
        <url-pattern>/add</url-pattern>
</servlet-mapping>

//ProductDB 内部的方法(数据库查询函数的类)

public static void insertProduct(Product p) {

    ConnectionPool pool = ConnectionPool.getInstance();
    Connection connection = pool.getConnection();
    PreparedStatement ps = null;
    ResultSet rs = null;

    String query=" INSERT INTO productsMaintenance VALUES( '"+ p.getCode()+"','"+ p.getDescription()+"','"+ p.getPriceCurrencyFormat()+"' ) ";

    try {

        ps = connection.prepareStatement(query);
        rs = ps.executeQuery();

    }

    catch (SQLException e) {
        System.err.println(e);
    } finally {
        DBUtil.closeResultSet(rs);
        DBUtil.closePreparedStatement(ps);
        pool.freeConnection(connection);
    }
}

最佳答案

您可以通过 using a debugger 找出根本原因。除此之外,下面给出的一些最佳实践也可以帮助您解决问题。

对于 SQL 数据操作语言 (DML) 语句,例如 INSERTUPDATEDELETE,您应该使用executeUpdateexecute

此外,您的 PreparedStatement 实现与 Statement 没有什么不同,即您实际上没有利用 PreparedStatement 的功能和优势。应该是这样的

String query = "INSERT INTO productsMaintenance (Code, Description, PriceCurrencyFormat) VALUES (?, ?, ?)";
ps = conn.prepareStatement(query);
ps.setString (1, p.getCode());
ps.setString (2, p.getDescription());
ps.setString (3, p.getPriceCurrencyFormat());

// execute the PreparedStatement
ps.execute();

这样您就可以阻止 SQL injection 的尝试您也可以摆脱在每个数据之前和之后显式插入 ' 的情况。

检查this了解更多信息。

关于java - 使用 Java Servlet/jsp 将产品添加到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61229044/

相关文章:

java - 当我将文本从 java servlet 加载到 JTextPane 时,为什么会丢失换行符?

java - 如何部署 Java Web 应用程序。部署步骤

java - AWS ELB servlet 客户端断开检测

java - Spring Data REST 在运行时选择字段

java - 严重: Context [/AnilProject] startup failed due to previous errors whil deploying war on tomcat

java - DateTime 未使用 jsp 插入数据库

HTML textarea curson 由于某种原因缩进

java - 将锁定计数设置为大于 1 的值

java - 将字符串添加到 ArrayList<LinkedList<String>> Java

java - RHEL 5 - 路径环境变量更改不生效