Setting up jQuery jTable plugin in Servlets and JSP
In this article we will learn to setup jTable and dependent libraries in a Java web application.
For all who do not know what exactly jTable is, it is a jQuery plugin which is used to create AJAX based CRUD tables without coding HTML or Javascript.
Let us take a look at what happens if we are not using a Jquery Plugin for front end Table data management.
Using Java & Javascript:
Pre-requisites for usage:
- Must be a expertise in java & javascript
- A lot of time on hand
- Last but not the least patience
Now if the project requirement for this table changes at last moment one would pull their hair out and end up resembling a Joker
jTable has a few advantages over the above, some of them being:
- Automatically creates HTML table and loads records from server using AJAX.
- jTable uses just a div id and automatically generates html table inside the div
- It uses jQuery UI dialog that pops up when the user clicks on add, edit or update record buttons
- Shows animations for create/delete/edit operations on the table.
- Supports server side paging & sorting using AJAX.
- Supports master/child tables.
- Supports several pre defined color themes; In this example I have used metro blue theme for my project.
And there are lot other features than mention above, to know more please read on its official home page.
Steps done to set up our application for jTable
Libraries required
Now to start with demonstration of above topic, let us Create a Dynamic Web Project in Eclipse, with following project structure.
As show in the image download the required library mentioned and place it in js and css folder of eclipse work-space, and refer these files in the head section in the jsp as shown below.
Setup done from the browser perspective: jTable
jTable plugin allows you to issue an ajax request via jQuery plugin and expects a JSON object as a response, hence the following configuration needs to be made in Jsp file
Jsp Page
jQuery jTable Setup in java jQuery jTable Setup in java
As you can see, jTable just needs a div element as the only HTML tag. It fields options are explained below:
title: Title of the table.
actions: URLs of actions that are used to create/delete/update/list records.
fields: It defines the field names that represent columns of the record. Note that the field name should exactly match the instance variable defined in the model class.
In the jsp above I have only provided action url for listAction for demonstration purpose, we can include action for add,edit and delete functionality as well, which we will learn in a while. The load method of jTable is fired when page is loaded which in turn trigger listAction to get records from the server.
Setup done from the server’s perspective: Servlet
In Servlet, we are going to use a JSON library to convert Java objects(studentList) to JSON strings that will be parsed by jTable pugin in the JSP page and will be displayed on the web page.This conversion of Java Object to Json format is done using Google gson jar.
Controller
package com.servlet; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.model.Student; public class Controller extends HttpServlet { private static final long serialVersionUID = 1L; private HashMapJSONROOT = new HashMap (); public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); if ( action != null) { List studentList = new ArrayList (); Gson gson = new GsonBuilder().setPrettyPrinting().create(); response.setContentType("application/json"); if (action.equals("list")) { try { // Add data to Student list studentList.add(new Student(1, "Haripriya", "IT", "[email protected]")); studentList.add(new Student(2, "Dinesh", "ECE", "[email protected]")); studentList.add(new Student(3, "Prabhu", "MECH", "[email protected]")); studentList.add(new Student(4, "Badru", "ECE", "[email protected]")); studentList.add(new Student(5, "Lahir nisha", "CSC", "[email protected]")); studentList.add(new Student(6, "Nilafar nisha", "CSC", "[email protected]")); studentList.add(new Student(7, "Jamil", "ECE", "[email protected]")); studentList.add(new Student(8, "Mahes", "ECE", "[email protected]")); studentList.add(new Student(9, "Lourde", "IT", "[email protected]")); //Return in the format required by jTable plugin JSONROOT.put("Result", "OK"); JSONROOT.put("Records", studentList); // Convert Java Object to Json String jsonArray = gson.toJson(JSONROOT); System.out.println(jsonArray); response.getWriter().print(jsonArray); } catch(Exception ex){ JSONROOT.put("Result", "ERROR"); JSONROOT.put("Message", ex.getMessage()); String error = gson.toJson(JSONROOT); response.getWriter().print(error); } } } } }
In case of read operations in jTable, Result property must be “OK” if operation is successful. If an error occurs, then Result property must be “ERROR”. If Result is “OK”, the Records property will contain an array of records defined in the servlet. If it’s ERROR, a Message property will contain an error message to show to the user. A sample return value for listAction is show below
{“Result”:”OK”,”Records”:[
{
“studentId”: 2,
“name”: “Bashit”,
“department”: “EEE”,
“emailId”: “[email protected]”
},
{
“studentId”: 3,
“name”: “Haripriya”,
“department”: “IT”,
“emailId”: “[email protected]”
}
]}
Model Class
Create the Model class , which will have getters and setters for fields used in jsp
package com.model; public class Student { public Student() { } public Student(int studentId, String name, String department, String emailId) { this.studentId = studentId; this.name = name; this.department = department; this.emailId = emailId; } private int studentId; private String name; private String department; private String emailId; public int getStudentId() { return studentId; } public String getName() { return name; } public String getDepartment() { return department; } public String getEmailId() { return emailId; } public void setStudentId(int studentId) { this.studentId = studentId; } public void setName(String name) { this.name = name; } public void setDepartment(String department) { this.department = department; } public void setEmailId(String emailId) { this.emailId = emailId; } }
web.xml
Make sure you have done servlet mapping properly in web.xml file. An example of this is given below,
index.jsp Controller com.servlet.Controller Controller /Controller
Demo
Now on including action for create, update and delete in jsp page as below
actions : { listAction: 'Controller?action=list', createAction:'Controller?action=create', updateAction: 'Controller?action=update', deleteAction: 'Controller?action=delete' }
No on running with the above changes, the demo looks like below
On clicking ‘Add new record’
On clicking edit button
On clicking delete button
Note :
In the above program I have not included the logic for create, delete and update functions at server side. In the article CRUD Operations in Java Web Applications using jTable jQuery plugin via Ajax I have implemented CRUD operation, and in the article Pagination in Java Web Applications using jQuery jTable plugin I have implemented paging feature using the same plugin.
Reference
jTable official website
AJAX based CRUD tables using ASP.NET MVC 3 and jTable jQuery plug-in
Wikipedia : JSON
you have tweak the jtable js file in order to change the look and feel of model dialog
hi,
Thanks for the nice explanation, I am able to run this successfully but in href if i give some actions like “student.do?action=list” it doesn’t work, i can call directly with jsp file.. please suggest something on this i cant call jsp directly….
You can call jTable action only via jQuery Javascript in an asynchronous manner.
Hi great explanation, i copy and paste the code (of course learned), when i run on NetBeans run fine, but not display anything (only the jQuery jTable Setup in java) i try debuk put some points on the controller and on the student class but neer of never stop.
Any advice?
thanks
Please share your code
I have difficulty in using this. I have data like this in my java Console
{“Result”:”OK”,”Records”:[
{
“matricule”: “admin”,
“nom_jury”: “Administrateur”,
“password”: “admin”,
“fonctionjury”: “Administrateur SI”,
“profiljury”: “Administrateur”
}
]}
Not in table. Please help me
Hey ! its great.
But i tried with my database table , but it is not working.
So what are the changes required in the index.jsp page.
Hi,
1) Please take the note that all data are stored in to “studentList ” object.
2) after declaring try block you can call any method(MyDatabase()) make sure that method must return List type object.
3) In that method (MyDatabase()) you need to provide your all database connection related operation.
Thanx,
Malik