Search code examples
javajquerytwitter-bootstrapjsptablesorter

Update html table via servlet and jsp


I am creating a simple Java webpage which has to get input from user and then push the data to table which is on the same page. Everything is working perfectly. Each time the user gives input the page, the servlet does it job and reloads the page and table is updated. My question is, how to update table without reloading the page.

Secondly, i have a input field, which searches the table. Again, it is working. However, I'm also trying to add jquerys tablesorter to my table. I have done everything according to tutorials but the sorting isn't happening. Can this be because of the search field? I am also using Bootstrap to design my table, can this be the cause (although the jquerys tablesorter states, that it works with Bootstrap also).

The servlet returns with:

request.getRequestDispatcher("WEB-INF/views/Login.jsp").forward(request, response);;

UPDATE My JSP looks like this: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <title>My title</title>
  <link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css"    rel="stylesheet">
  <link href="css/myStyle.css" rel="stylesheet">    
</head>
<body>
  <form  method="post" >
   <div class="container">
    <div class="jumbotron">
            <label for="name">Nimi</label>
            <input type="text" name="name" class="form-control"/>
            <label for="email">Email</label>
            <input type="email" name="email" class="form-control"/>
            <label for="syKP">Sünnikuupäev</label>
            <input type="text" name="syKP" class="form-control"/>
            <label for="aadress">Aadress</label>
            <input type="text" name="aadress" class="form-control"/><br>
            <button type="submit" class="btn btn-info btn-md">Add</button>
    </div>
</div>
</form>
<div class="container">
 <div class="jumbotron">
  <input type="text" id="search" placeholder="Type to search"><br>
   <table class="table table-hover tablesorter" id="tabel">
<thead>
 <tr>
    <th>Nimi</th>
    <th>Aadress</th>
    <th>Synd</th>
    <th>Email</th>
    <th>Muuda</th>
    <th>Kustuta</th>
 </tr>
</thead>
<c:forEach items="${dataLst.getData()}" var="person">
 <tbody id="table">
  <tr >
    <td><c:out value="${person.getNimi()}"/></td>
    <td><c:out value="${person.getAadress()}"/></td>
    <td><c:out value="${person.getSynniKP() }"/></td>
    <td><c:out value="${person.getEmail()}"/></td>
    <td><button class="btn button-default"><span class="glyphicon glyphicon-pencil"></span></button></td>
    <td><button class="btn button-default"><span class="glyphicon glyphicon-    remove-sign"></span></button></td>
  </tr>
 </tbody>
</c:forEach>   
</table>
</div>
</div>
<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="javascript/main.js"></script>
</body>
</html>

and my servlet file like this:

package com.energy;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet(urlPatterns="/login.do")
public class LoginServlet extends HttpServlet{

DataList dataLst = new DataList();

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException{
    request.getRequestDispatcher("/WEB-INF/views/Login.jsp").forward(request,response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse  response) 
throws ServletException, IOException {
    String name = request.getParameter("name");
    String email = request.getParameter("email");
    String aadress = request.getParameter("aadress");
    String syKP = request.getParameter("syKP");



    PersonData person = new PersonData(name, aadress, syKP, email);
    dataLst.addPerson(person);
    //request.setAttribute("name", request.getParameter("name"));
    //request.setAttribute("email", request.getParameter("email"));
    //System.out.println(dataLst.getData().get(0).getNimi());

    request.setAttribute("dataLst",dataLst);
    request.getRequestDispatcher("WEB-INF/views/Login.jsp").forward(request,     response);;
}

}

Solution

  • For updating the table dynamically:

    Usually, JSON is used to send response from the server. Use GSON.jar to convert a java object to corresponding JSON. This is replacing the request dispatcher in servlet as shown in the updated servlet class below-

    package com.energy;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    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;
    
    @WebServlet(urlPatterns="/login.do")
    @MultipartConfig
    public class LoginServlet extends HttpServlet{
    
      private static final long serialVersionUID = 1L;
      DataList dataLst = new DataList();
    
      protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException{
      }
    
      protected void doPost(HttpServletRequest request, HttpServletResponse  response) 
            throws ServletException, IOException {
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String address = request.getParameter("aadress");
        String syKP = request.getParameter("syKP");
    
        PersonData person = new PersonData(name, address, syKP, email);
        dataLst.addPerson(person);
        //request.setAttribute("name", request.getParameter("name"));
        //request.setAttribute("email", request.getParameter("email"));
        //System.out.println(dataLst.getData().get(0).getNimi());
    
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        Gson data = new Gson();
        String tmp = data.toJson(dataLst); // won't work if you don't assign it to a string.
        response.getWriter().write(tmp);
        //request.getRequestDispatcher("WEB-INF/views/Login.jsp").forward(request,     response);;
      }
    
    }
    

    For submitting the form using ajax (to avoid page reloads), I've modified your form as this-

    <form  method="post" id="loginForm" enctype="multipart/form-data">
    

    The multipart-form-data helps serialize the form in a standard way (HTML5). Now make your servlet capable of accepting multipartrequests by addding @MultipartConfig annotation as shown below-

    @WebServlet(urlPatterns="/login.do")
    @MultipartConfig
    public class LoginServlet extends HttpServlet{
        // Rest of the code.
    }
    

    We're almost there! Now if you prefer JavaScript, add the following function to your main.js to make the ajax calls.

    function addData(){
      if(window.XMLHttpRequest) { //Assuming you're not on one of the old IEs.
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange=function() {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                var myArr = JSON.parse(xhttp.responseText);
                //console.log(myArr);
                addToTable(myArr); // function to add data to table.
    
            }
        }
        xhttp.open("POST","login.do",true);
        var formData = new FormData(document.getElementById('loginForm'));
        xhttp.send(formData);
      }
      else console.log('not working');
    }
    

    Make sure you call this function on click of Add button.

    <button type="submit" class="btn btn-info btn-md" onclick="addData();">Add</button>
    

    Here's one of the ways to write addToTable function.

    function addToTable(data) {
      var dataTable = document.getElementById("tabel");
      for(var i = 0; i<data.pList.length; i++) {
        var row = dataTable.insertRow();
        var tmp = data.pList[i];
    
        var cell0 = row.insertCell(); //nimi
        var cell1 = row.insertCell(); //aadress
        var cell2 = row.insertCell(); //synd
        var cell3 = row.insertCell(); //email
        var cell4 = row.insertCell(); //muuda
        var cell5 = row.insertCell(); //kustuta
    
        cell0.innerHTML = tmp.name;
        cell1.innerHTML = tmp.address;
        cell2.innerHTML = tmp.syKP;
        cell3.innerHTML = tmp.email;
        cell4.innerHTML = '<button class="btn button-default"><span class="glyphicon glyphicon-pencil"></span></button>';
        cell5.innerHTML = '<button class="btn button-default"><span class="glyphicon glyphicon-remove-sign"></span></button>';
      }
    }
    

    Note that pList is the name of list in DataList.java where I'm storing PersonDetails.

    If you're comfortable with jQuery, same thing can be done as follows-

    $(function() {
      $('button[type=button]').on('click',function() {
        var upForm = $('form').get(0);
        var $form = new FormData(upForm);
        $.ajax({
            url:'login.do', 
            data: $form,
            type: 'POST',
            processData: false,
            contentType: false,
            success: function(responseText) {
                var data = responseText.pList;
                $.each(data, function(index, tmp) {
                    var table1 = $('table>tbody').get(0);
                    var row = table1.insertRow();
                    var cell0 = row.insertCell(); //nimi
                    var cell1 = row.insertCell(); //aadress
                    var cell2 = row.insertCell(); //synd
                    var cell3 = row.insertCell(); //email
                    var cell4 = row.insertCell(); //muuda
                    var cell5 = row.insertCell(); //kustuta
    
                    cell0.innerHTML = tmp.name;
                    cell1.innerHTML = tmp.address;
                    cell2.innerHTML = tmp.syKP;
                    cell3.innerHTML = tmp.email;
                    cell4.innerHTML = '<button class="btn button-default"><span class="glyphicon glyphicon-pencil"></span></button>';
                    cell5.innerHTML = '<button class="btn button-default"><span class="glyphicon glyphicon-remove-sign"></span></button>';
                });
                $('#tabel').tablesorter();
            }
        });
      });
    })
    

    The servlet and html configuration will remain the same.

    P.S. I've removed the code jstl code because I've always had hard time tweaking jQuery and bootstrap with the jstl translated code.

    Also, tablesorter works fine for me. Though I don't have the search box implemented, I don't think it will cause any problem for tablesorter.