0

I'm new to Jsp and Servlets and I need some like this:

enter image description here

The select works fine. But I have no idea how to implement the dynamic table with servlets and Jquery/Ajax.

My JSP file, with Jquery for async update the second select and show the table fields:

     <%@ 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, for process the requests and async update using 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();
        }


    }

  }

Thank's for any example, link or tip

Matías W.
  • 350
  • 2
  • 17

1 Answers1

1

Instead of manually setting each parameter and then encoding it in a json object, why not just ajaxify a form?

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

And in your servlet, you just get the form fields like you normally do:

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

   }

}

I highly recommend looking at this great explanation about using Servlets with AJAX. There is an example there on how to return a JSON object if that's what you want to do.

Jonathan Laliberte
  • 2,672
  • 4
  • 19
  • 44