Pages Navigation Menu

Coding is much easier than you think

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.
 
Integrating-jQuery-jTable-plugin-with-Struts2-framework
 
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
 
Joker jTable
 
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.
 
jtable setup in servlet
 
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

 

<!DOCTYPE html>
<html>
<head>
<title>jQuery jTable Setup in java</title>
<!-- jTable Metro styles. -->
<link href="css/metro/blue/jtable.css" rel="stylesheet" type="text/css" />
<link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
<!-- jTable script file. -->
<script src="js/jquery-1.8.2.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
<script src="js/jquery.jtable.js" type="text/javascript"></script>
<script type="text/javascript">
	$(document).ready(function() {
		$('#StudentTableContainer').jtable({
			title : 'Students List',
			actions : {
				listAction : 'Controller?action=list'
			},
			fields : {
				studentId : {
					title : 'Student Id',
					width : '30%',
					key : true,
					list : true,
					create : true
				},
				name : {
					title : 'Name',
					width : '30%',
					edit : false
				},
				department : {
					title : 'Department',
					width : '30%',
					edit : true
				},
				emailId : {
					title : 'Email',
					width : '20%',
					edit : true
				}
			}
		});
		$('#StudentTableContainer').jtable('load');
	});
</script>

</head>
<body>
<div style="text-align: center;">
	<h4>jQuery jTable Setup in java</h4>
	<div id="StudentTableContainer"></div>
</div>
</body>
</html>

 
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 HashMap<String, Object> JSONROOT = new HashMap<String, Object>();

	public void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	
	String action = request.getParameter("action");
	if ( action != null) 
	{
		List<Student> studentList = new ArrayList<Student>();

		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", "xyz@xyz.com"));
			studentList.add(new Student(2, "Dinesh", "ECE", "xyz@gmail.com"));
			studentList.add(new Student(3, "Prabhu", "MECH", "abc@gmail.com"));
			studentList.add(new Student(4, "Badru", "ECE", "efg@gmail.com"));
			studentList.add(new Student(5, "Lahir nisha", "CSC", "xyz@gmail.com"));
			studentList.add(new Student(6, "Nilafar nisha", "CSC", "123@gmail.com"));
			studentList.add(new Student(7, "Jamil", "ECE", "789@gmail.com"));
			studentList.add(new Student(8, "Mahes", "ECE", "123@gmail.com"));
			studentList.add(new Student(9, "Lourde", "IT", "xyz@gmail.com"));

			//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”: “xyz@abc.com”
},
{
“studentId”: 3,
“name”: “Haripriya”,
“department”: “IT”,
“emailId”: “hp@abc.com”
}
]}
 

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,
 

<welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
  <servlet-name>Controller</servlet-name>
  <servlet-class>com.servlet.Controller</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>Controller</servlet-name>
  <url-pattern>/Controller</url-pattern>
</servlet-mapping>

 

Demo

 
jquery-jtable-in-struts-2
 
 
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
Integrating-jQuery-jTable-plugin-with-Struts2-framework
 
On clicking ‘Add new record’
Struts-2-using-jTable-jQuery-plug-in-Create-record
 
On clicking edit button
Struts-2-jTable-jQuery-plug-in-Update-record
 
On clicking delete button
Struts-2-jTable-jQuery-plug-in-Delete-record
 
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.
 
download
 

Reference

jTable official website
AJAX based CRUD tables using ASP.NET MVC 3 and jTable jQuery plug-in
Wikipedia : JSON
 

About Mohaideen Jamil


Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

  • http://www.simplecodestuffs.com/ Mohaideen Jamil

    you have tweak the jtable js file in order to change the look and feel of model dialog

  • vani

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

    • http://www.simplecodestuffs.com/ Mohaideen Jamil

      You can call jTable action only via jQuery Javascript in an asynchronous manner.

  • Miguel Enriquez

    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

  • BILANGA Ange

    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

  • vaiovaio

    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.