java - 使用 servlet 更新文本字段

标签 java servlets

我是 Java 的新手,我正在尝试使用 servlet 更新文本字段。插入和删除已完成,但更新不起作用。我只是在使用 HTML 和 servlet。 这是我的 servlet

ComputerController.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    ComputerDAO comDAO = new ComputerDAO();
    //get Service
    String service = request.getParameter("service");
    if (service == null || service == "") {
        service = "listAllComputer";
    }
    if (service.equals("addComputer")) {

        //get parameter
        String name = request.getParameter("cname");
        String quan = request.getParameter("quantity");
        String price = request.getParameter("price");
        String func = request.getParameter("functions");
        //Check invalid here
        Computer com = new Computer(0, name, Integer.parseInt(quan), Double.parseDouble(price), func);
        //add into DB
        int n = comDAO.addComputer(com);
        if (n > 0) {
            out.println("<h1> INSERTED</h1>");
        }
    }

    if (service.equalsIgnoreCase("listallcomputer")) {
        ArrayList<Computer> arr = comDAO.getAllComputer("select * from Computer");
        if (arr.size() == 0) {
            out.println("<h1> NO RECORD FOUND </h1>");

        } else {
            out.println(" <table width='100%' border='1'>");
            out.println("<caption>");
            out.println("  <h2>Computer List</h2>");
            out.println(" </caption>");
            out.println("<tr>");
            out.println("  <th scope='col' width='5%'>id</th>");
            out.println(" <th scope='col'width='30%'>Computer Name</th>");
            out.println(" <th scope='col'width='10%'>Quantity</th>");
            out.println(" <th scope='col'width='15%'>Price</th>");
            out.println("  <th scope='col'width='30%'>Functions</th>");
            out.println("  <th scope='col' colspan=2 width='10%'>Action</th>");
            out.println(" </tr>");
            for (int i = 0; i < arr.size(); i++) {
                Computer com = arr.get(i);
                out.println("<tr>");
                out.println("  <td>" + com.getCid() + "</td>");
                out.println("  <td>" + com.getCname() + "</td>");
                out.println("  <td>" + com.getQuantity() + "</td>");
                out.println(" <td>" + com.getPrice() + "</td>");
                out.println(" <td>" + com.getFunc() + "</td>");
                out.println(" <td><a href = ComputerController?service=update&id=" + com.getCid() + ">Update</a></td>");
                out.println(" <td><a onclick= \"return confirm('Are you sure you want to delete this item?');\" href=ComputerController?service=delete&id=" + com.getCid() + ">Delete</a></td>");
                out.println(" </tr>");
            }
            out.println("</table>");
            out.println("<a href= index.jsp>Back to Main page</a>");
        }
    }
    if (service.equalsIgnoreCase("delete")) {
        String deleteId = request.getParameter("id");
        try {
            if (deleteId != null) {
                int deleteIdInt = Integer.parseInt(deleteId);
                int isOk = comDAO.removeComputer(deleteIdInt);
                if (isOk != 0) {
                    out.print("Deleted computer with id = " + deleteIdInt);
                } else {
                    out.print("Error");
                }
            }
        } catch (Exception ex) {
            out.print(ex.getMessage());
        }
    }
    if (service.equalsIgnoreCase("update")) {

        out.println(" <html>");
        out.println("<body>");
        out.println("<form id='form1' name='form1' method='post' action='ComputerController' style='width: 500px; margin: 20px auto 0 auto;'>");
        out.println("<h2>Update Computer</h2>");
        out.println(" <table width='100%' border='0'>");
        out.println("<tr>");
        out.println("  <th width='28%' scope='row'>Computer Name</th>");
        out.println(" <td width='72%'><input type='text' name='cnameUpdate' id='cnameUpdate' /></td>");
        out.println(" </tr>");
        out.println(" <tr>");
        out.println(" <th scope='row'>Quantity</th>");
        out.println("   <td><input type='text' name='quanUpdate' id='quanUpdate' /></td>");
        out.println("</tr>");
        out.println("<tr>");
        out.println("   <th scope='row'>Price</th>");
        out.println("  <td><input type='text' name='priceUpdate' id='priceUpdate' /></td>");
        out.println("</tr>");
        out.println("<tr>");
        out.println("   <th scope='row'>Functions</th>");
        out.println("   <td><textarea rows='4' name='funcUpdate' id='funcUpdate'></textarea></td>");
        out.println(" </tr>");
        out.println("<tr>");
        out.println("  <th scope='row'>&nbsp;</th>");
        out.println("  <td><input type='submit' name='button' id='button' value='Update' />");
        out.println("       <input name='updateComputer' type='hidden' id='updateComputer' value='updateComputer' /></td>");
        out.println("  </tr>");
        out.println(" </table>");
        out.println(" </form>");
        out.println(" </body>");
        out.println("</html>");

    }
    if (service.equalsIgnoreCase("updateComputer")) {
        String uid = request.getParameter("cid");
        String uname = request.getParameter("cname");
        String uquan = request.getParameter("quantity");
        String uprice = request.getParameter("price");
        String ufunc = request.getParameter("functions");
        Computer com = new Computer(Integer.parseInt(uid), uname, Integer.parseInt(uquan), Double.parseDouble(uprice), ufunc);
        int n = comDAO.updateComputer(com);
        if (n > 0) {
            out.print("<h2>Updated</h2>");
        }
    }
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

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

这是我的 DAO。我认为那个文件没有问题

ComputerDAO.java

public int addComputer(Computer com) {
    int n = 0;
    try {
        Statement add = conn.createStatement();
        String sql = "INSERT INTO Computer(cname,quantity,price,functions)" + "values(?,?,?,?)";
        PreparedStatement pre = conn.prepareStatement(sql);
        pre.setString(1, com.getCname());
        pre.setInt(2, com.getQuantity());
        pre.setDouble(3, com.getPrice());
        pre.setString(4, com.getFunc());
        n = pre.executeUpdate();
    } catch (SQLException ex) {
        Logger.getLogger(ComputerDAO.class.getName()).log(Level.SEVERE, null, ex);
    }
    return n;
}

public ResultSet getData(String sql) {
    try {
        state = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        rs = state.executeQuery(sql);
    } catch (SQLException ex) {
        Logger.getLogger(ComputerDAO.class.getName()).log(Level.SEVERE, null, ex);
    }
    return rs;
}


public ArrayList<Computer> getAllComputer(String sql) {
    ArrayList<Computer> arr = new ArrayList<Computer>();
    try {
        state = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        rs = state.executeQuery(sql);
        while (rs.next()) {
            int id = rs.getInt("cid");
            String cname = rs.getString(2);
            int quan = rs.getInt(3);
            double price = rs.getDouble(4);
            String func = rs.getString(5);
            Computer com = new Computer(id, cname, quan, price, func);
            arr.add(com);
        }
    } catch (SQLException ex) {
        Logger.getLogger(ComputerDAO.class.getName()).log(Level.SEVERE, null, ex);
    }
    return arr;
}

public int removeComputer(int id) {
    int n = 0;
    try {
        //code here
        String query = "DELETE FROM Computer WHERE cid = '" + id + "'";
        Statement st = conn.createStatement();
        int rs = st.executeUpdate(query);
        return rs;
    } catch (SQLException ex) {
        Logger.getLogger(ComputerDAO.class.getName()).log(Level.SEVERE, null, ex);
    }
    return n;
}

public int updateComputer(Computer com) {
    int n = 0;
    try {
        //code here
        String query = "UPDATE Computer SET cname ='" + com.getCname() + "', quantity = " + com.getQuantity() + ", price = '" + com.getPrice() + ", functions = '" + com.getFunc() + "' WHERE cid = " + com.getCid() + "";
        Statement st = conn.createStatement();
        int rs = st.executeUpdate(query);
        return rs;
    } catch (SQLException ex) {
        System.out.println(ex.getMessage());
        Logger.getLogger(ComputerDAO.class.getName()).log(Level.SEVERE, null, ex);
    }
    return n;
}

最佳答案

您应该在写入更新页面时为所有 Controller 设置值。像这样:

out.println("<input name='updateComputer' type='hidden' id='updateComputer' value='"+compId+"'/></td>");

请注意上面代码中的 value='"+compId+"'"。我没有在您的代码中的任何地方看到您在表单上设置值。除非我是缺少一些东西。

关于java - 使用 servlet 更新文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25998588/

相关文章:

java - 根据条件更改 JSlider 的最小值和最大值

jsp - 如何查找 session 变量是否存在

java - Jsp/Servlet Hello World 与 JBoss

java - 随机子矩阵

java - 从绝对路径加载类

java - 如何在 Android 中没有 UI 或用户交互的情况下拍摄大量照片?

jsp - 如何在 Windows tomcat 中部署在 RHEL 5 中制作的 java tomcat 项目?

java - 使用curl POST添加Google Blobstore

java - 如何打开位于 WAR 文件中的只读 SQLite 数据库?

java - 数据库 - 有 2 个表,需要另一个具有 ID 和另一个字段的表