如何保存记录并使用 java 中的记录值更新同一页面

How to save records and update the same page with recorded values in java


我正在尝试创建一个页面来注册新产品并在同一页面中显示结果列表。
这是我的 product.jsp 页面。

<%@page contentType="text/html" pageEncoding="UTF-8"%>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script src="//code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
    </head>
    <body>
        <table>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Description</th>
                <th>Price</th>
            </tr>
            <div>
                <c:forEach items="${products}" var="product">
                    <tr>
                        <td>${product.id}</td>
                        <td><c:out value="${product.name}" /></td>
                        <td><c:out value="${product.description}" /></td>
                        <td><c:out  value="${product.price}" /></td>
                    </tr>
                </c:forEach>
            </div>
        </table>
        <br/><br/>
        <form  id="form1" action="${pageContext.request.contextPath}/" method="post">
            <table> 
                <tr> <td>Product Name : <input type="text" name="pname" id="pname" /></td></tr>
                <tr> <td>Product Description : <input type="text" name="pdesc" id="pdesc"/></td></tr>
                <tr><td>Product Price : <input type="text" name="price" id="price"/></td></tr>
                <tr><td> <input type="submit" value="save"/></td></tr>

            </table>
            <h4 style="color: red" id="result"><c:out value="${msg}"/></h4>
        </form> 
        <script>
            $(document).ready(function () {            
                $('#form1').submit(function () {       .
                    $form = $(this);                            
                    $.post($form.attr('action'),
                            $form.serialize(),
                            function (responseText) {      
                                $('#result').text(responseText); 
                                $('#pname').val('');
                                $('#pdesc').val('');
                                $('#price').val('');
                            });
                    return false;                                    
                });
            });
        </script>
    </body>
</html>

这是我的 products.java servlet。
doGet() 方法通常在页面加载时调用,它 returns 已注册的项目列表。
另一方面,doPost() 方法保存记录并将 returns 结果返回到 product.jsp 页面。

   @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            List<Product> products = productDAO.list();
            request.setAttribute("products", products); 
            request.getRequestDispatcher("/products.jsp").forward(request, response);
        } catch (SQLException e) {
            throw new ServletException("Cannot obtain products from DB", e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest requset, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        try {
            Product p = new Product();
            p.setName(requset.getParameter("pname"));
            p.setDescription(requset.getParameter("pdesc"));
            p.setPrice(new BigDecimal(requset.getParameter("price")));
            if (productDAO.Save(p) > 0) {
               response.getWriter().write(String.valueOf("sucess"));
            } else {
                response.getWriter().write(String.valueOf("saved fail"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write(String.valueOf(e));
        }

这也是我的 web.xml 文件,指示 products.java servlet 文件在应用程序启动时加载。

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>products</servlet-name>
        <servlet-class>com.shop.controller.products</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>products</servlet-name>
        <url-pattern/>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <resource-ref>
        <description>DB Connection</description>
        <res-ref-name>jdbc/MyDatasource</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
</web-app>

此网页运行良好,但我遇到的问题是我想在注册项目后更新给定列表。
目前我只发送成功或错误消息。我得到一个建议,说我应该使用 json。但据我所知,它不会更新给定 table。
请帮忙。谢谢。

您的代码确实按预期正常工作。

您需要做的是在成功回调时触发页面的重新加载(不是很用户友好)或使用 JavaScript 更新您的 table 以修改 [=页面的 18=](大多数现代系统如何工作)。

使用 JavaScript 框架动态呈现页面并根据服务器中的变化保持页面更新,这样的任务更容易完成。有非常简单易用的库,如 Backbone.js,也有更高级的库,如 AngularJS 和 React。

查看 BalusC 的 answer here,真是天赐之物。正如您从中看到的,有许多不同的方法来处理您的响应数据。下面我会用你的代码给你一个例子。

例如,您可以这样做:

product.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script src="//code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
    </head>
    <body>
        <table>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Description</th>
                <th>Price</th>
            </tr>
            <div>
                <c:forEach items="${products}" var="product">
                    <tr>
                        <td>${product.id}</td>
                        <td><c:out value="${product.name}" /></td>
                        <td><c:out value="${product.description}" /></td>
                        <td><c:out  value="${product.price}" /></td>
                    </tr>
                </c:forEach>
            </div>
        </table>
        <br/><br/>
        <form  id="form1" action="YourProductsServlet" method="post">
            <table> 
                <tr> <td>Product Name : <input type="text" name="pname" id="pname" /></td></tr>
                <tr> <td>Product Description : <input type="text" name="pdesc" id="pdesc"/></td></tr>
                <tr><td>Product Price : <input type="text" name="price" id="price"/></td></tr>
                <tr><td> <input type="submit" value="save"/></td></tr>

            </table>
            <div style="color: red" id="result"></div>
        </form> 
        <script>
    //ajaxifying an existing form
    $(document).on("submit", "#form1", function(event) {
       var $form = $(this);
       $.post($form.attr("action"), $form.serialize(), function(responseJson) {
        // handle response data 

   var $table = $("<table>").appendTo($("#result")); // Create HTML <table> element and append it to HTML DOM element with ID "result".
        $.each(responseJson, function(index, product) {    // Iterate over the JSON array.
            $("<tr>").appendTo($table)                     // Create HTML <tr> element, set its text content with currently iterated item and append it to the <table>.
                .append($("<td>").text(product.id))        // Create HTML <td> element, set its text content with id of currently iterated product and append it to the <tr>.
                .append($("<td>").text(product.name))      // Create HTML <td> element, set its text content with name of currently iterated product and append it to the <tr>.
                .append($("<td>").text(product.price));    // Create HTML <td> element, set its text content with price of currently iterated product and append it to the <tr>.
        });

       });    
       event.preventDefault(); // Important! Prevents submitting the form.
    });
        </script>
    </body>
</html>

products.java

Note: Servlets by convention start with a capital letter. Also in your web.xml there is no url mapping set.. So as shown in the form above i'm going to assume it's set as "YourProductsServlet"

 @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      //in this case we are going to use this doGet method to handle your ajax response and when you initially load your data so we need to check if it's ajax or not, we can do that with this:
   boolean ajax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));

        try {

            List<Product> products = productDAO.list();
            request.setAttribute("products", products); 



     if (ajax) {
    //where the magic happens
   //Returning List<Entity> as JSON
    String json = new Gson().toJson(products);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
    }else{
    //not an ajax request so process normally
    request.getRequestDispatcher("/products.jsp").forward(request, response);
    }

        } catch (SQLException e) {
            throw new ServletException("Cannot obtain products from DB", e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest requset, HttpServletResponse response) throws ServletException, IOException {
  //your form submits your new product to here, where you will save in your database
        try {
            Product p = new Product();
            p.setName(requset.getParameter("pname"));
            p.setDescription(requset.getParameter("pdesc"));
            p.setPrice(new BigDecimal(requset.getParameter("price")));

            productDAO.Save(p);
            //if (productDAO.Save(p) > 0) {
               //response.getWriter().write(String.valueOf("sucess"));
            //} else {
                //response.getWriter().write(String.valueOf("saved fail"));
            //}
        } catch (Exception e) {
            e.printStackTrace();
            //response.getWriter().write(String.valueOf(e));
        }

    doGet(request,response); //forward request and response to doGet method
}

如果 works/helps 或者您有任何疑问,请告诉我。