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

时间:2018-05-16 15:57:51

标签: java ajax jsp jstl


我正在尝试创建一个注册新产品的页面,并在同一页面中显示结果列表。
这是我的 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()方法通常在加载页面时调用,并返回已注册的项目列表。
另一方面,doPost()方法保存记录并将结果返回到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。但据我所知,它不会更新相同的表格。
请帮忙。谢谢。

2 个答案:

答案 0 :(得分:2)

查看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

  

注意:按照惯例,Servlet以大写字母开头。也在你的   web.xml没有url映射集..所以如上面的表单所示   我将把它设置为&#34; YourProductsServlet&#34;

 @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
}

如果有效/帮助或有疑问,请告诉我。

答案 1 :(得分:0)

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

您需要做的是,要么在成功回调中触发页面的重新加载(不是非常用户友好),要么使用JavaScript更新您的表来修改页面的DOM(大多数现代系统如何工作)。

使用JavaScript框架可以更轻松地完成此类任务,以根据服务器中的更改动态呈现和保持页面更新。有很简单易用的库,比如Backbone.js,还有更高级的库,如AngularJS和React。