使用Jsp,Servlets和JQuery / Ajax创建动态表

时间:2017-08-24 19:55:43

标签: jquery ajax jsp servlets java-ee

我是Jsp和Servlets的新手,我需要这样的东西:

enter image description here

选择工作正常。但我不知道如何用servlet和Jquery / Ajax实现动态表。

我的JSP文件,使用Jquery for async更新第二个select并显示表字段:

     <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
     pageEncoding="ISO-8859-1"%>
  <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 <title>Insert title here</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 <script>
 $(document).ready(function() {
     $('#tableList').change(function() {
         var tableName = $(this).val();
         var servletUrl = 'servletQueryFields?table=' + tableName;

         $.getJSON(servletUrl, function(options) {
             var fieldListSelect = $('#fieldList');
             $('>option', fieldListSelect).remove();
             if (options) {
                 $.each(options, function(key, value) {
                    fieldListSelect.append($('<option/>').val(key).text(value));
                 });
             } else {
                fieldListSelect.append($('<option/>').text("None"));
             }
         });
     });
 });
 </script>
 </head>
 <body>
 <br/><br/><br/><br/>
 <b>SELECT TABLE NAME:</b> <br/>
 <select id="tableList">
     <c:forEach items="${tables}" var="table">
         <option value="${table.name}">${table.name}</option>
     </c:forEach>
 </select>
 <input type="button" id="bntAddTable" name="ADD" title="ADD" value="ADD" />
 <br/><br/>

 <b>TABLE FIELDS:</b> <br/>
 <select id="fieldList">
     <option>Select a table</option>
 </select>
 <br/>
 <b>SELECTED TABLES:</b> <br/>
 <table style="border:1px solid black;">
 <tr style="background-color:orange;"><td>TABLE_NAME</td></tr>
 <tr><td>ROW1</td></tr>
 </table>
 <br/><br/>
 <input type="button" id="sendBtn" name="SEND SELECTED TABLES" title="SEND     SELECTED TABLES" value="SEND SELECTED TABLES" /

My Servlet,用于使用GSON处理请求和异步更新:

  import java.io.IOException;
  import java.sql.Connection;
  import java.sql.SQLException;
  import java.util.Map;

  import javax.servlet.ServletException;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;

  import com.google.gson.Gson;
  import com.wmatias.utils.DBUtils;
  import com.wmatias.utils.MyUtils;

  @WebServlet(urlPatterns = {"/servletQueryFields"})
  public class servletQueryFields extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public servletQueryFields() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        Connection conn = MyUtils.getStoredConnection(request);

        String tableName = request.getParameter("table");
        Map<String, String> fields;
        try {
            fields = DBUtils.queryTableFields(tableName,conn);

            String json = new Gson().toJson(fields);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(json);

        } catch (SQLException e) {
            e.printStackTrace();
        }


    }

  }

感谢任何例子,链接或提示

1 个答案:

答案 0 :(得分:1)

不是手动设置每个参数然后在json对象中编码,为什么不只是ajaxify表单?

 <form action="servletQueryFields" method="get" id="someform">

<!--  you don't need id here, you can call the 'name' attribute from the servlet and get the selected value, so you don't need an 'add' button either -->
 <select id="tableList" name="tableOption">
     <c:forEach items="${tables}" var="table">
         <option value="${table.name}">${table.name}</option>
     </c:forEach>
 </select>

  <select id="fieldList" name="fieldOption">
     <option value="1">Select a table</option>
 </select>

 <input type="submit" value="Submit Form" />

</form>


<script>
$(document).on("submit", "#someform", function(event) {
    var $form = $(this);

    $.post($form.attr("action"), $form.serialize(), function(response) {
        // do your response logic here
    });

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

在您的servlet中,您只需获得通常所做的表单字段:

 @WebServlet(urlPatterns = {"/servletQueryFields"})
  public class servletQueryFields extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public servletQueryFields() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        Connection conn = MyUtils.getStoredConnection(request);
       //this will  get the option that the user selected
        String tableName = request.getParameter("tableOption");
       //value here is '1' because there is only one option in the select field with value set to ='1'
        String fieldList = request.getParameter("fieldOption");


    // do whatever else you want to do here


 String text = "some text";

  response.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write(text);       // Write response body.

   }

}

我强烈建议您查看有关在AJAX中使用Servlet的great explanation。有一个关于如何返回JSON对象的例子,如果这是你想要做的。