Pages Navigation Menu

Coding is much easier than you think

Pagination in Servlet and JSP using jQuery jTable plugin

Posted by in Ajax, J2EE, jQuery, jTable, Servlet | 7 comments

 
pagination in j2ee
 
This is the 3rd article on jQuery jTable plugin that describes on how to implement pagination feature to do server side paging and here I have not explained about how to setup jTable plugin in java web application. So If you have not read my previous articles “Setting up JQuery jTable plugin in Java web application” and “Ajax based curd operation in Java web application using JQuery jTables plugin”, I will recommend that you read that article first because first one explains how you can integrate the JTable plugin in Java web application and in second article explains on how to implement ajax based curd operation. This article will assume that the code for the integration of jQuery JTable plugin is implemented, and only the code required for implementing pagination in Java web application using jTable will be explained here.
 

Setup

 
Now download the sample application of my previous tutorial and import the project in eclipse. Now follow the steps in previous tutorial to create table in database and make sure you have atleast 5 records in the table.
 
Now on running this application, you will see a table displaying records without pagination such as the one shown below.
 
Integrating-jQuery-jTable-plugin-with-Struts2-framework
Now the following steps are needed to be followed to enable paging feature in jTable
 

Changes from the browser perspective: jTable

 
To enable paging, paging option must set to true. You can also set pageSize option (default value is 10) in jQuery Script code.

$('#StudentTableContainer').jtable({
    //...
    paging: true, //Set paging enabled
    pageSize: 3, //Set page size
    actions: {
        //...
    },
    fields: {
        //...
    }
});

 
Note: pageSize sets the initial number of records to be displayed per page.
 
Modified Jsp page is shown below
 

<!DOCTYPE html>
<html>
<head>
<title>Pagination in Java Web Applications using jTable plugin</title>
<!-- Include one of jTable 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" />
<!-- Include jTable script file. -->
<!-- Include 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',
           paging: true, //Enable paging
           pageSize: 3, //Set page size (default: 10)
           actions: {
               listAction: 'Controller?action=list',
               createAction:'Controller?action=create',
               updateAction: 'Controller?action=update',
               deleteAction: 'Controller?action=delete'
           },
		fields : {
			studentId : {
				title : 'Student Id',
				sort :true,
				width : '30%',
				key : true,
				list : true,
				edit : false,
				create : true
			},
			name : {
				title : 'Name',
				width : '30%',
				edit : true
			},
			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>Pagination in Java Web Applications jTable</h4>
	<div id="StudentTableContainer"></div>
</div>
</body>
</html>

 

Changes from the server’s perspective: Servlet

 
If paging is enabled in jsp then jTable sends two query string parameters to the server on listAction AJAX call:
jtStartIndex: Start index of records for current page.
jtPageSize: Count of maximum expected records.

And it expects additional information from server:
TotalRecordCount: Total count of records.
 
In our previous example the url specified in the ‘listAction‘ option has business logic to fetch all records from database. Now in order to handle pagination this ‘listAction’ option should return only the part of resultset for each page, So handle this there are two changes that has to be done in the server side .
 
1. In order to return only a subset of records according to the page offset (jtStartIndex and jtPageSize), sql query used in CRUDDao should be modified with query below,
In case of Oracle database:
“SELECT * from (Select M.*, Rownum R from STUDENT M) where r > ” + < jtStartIndex> +” and r <= "+< jtStartIndex + jtPageSize >;
 
In case of MySql database:

select * from STUDENT limit <jtStartIndex>,<jtPageSize>

 
Changes made in CRUDDao at getAllStudents function
 

public List<Student> getAllStudents(int startPageIndex, int recordsPerPage)
{
	List<Student> students = new ArrayList<Student>();
	int range = startPageIndex+recordsPerPage;
	String query="SELECT * from
        (Select M.*, Rownum R From STUDENT M) where
        r > " + startPageIndex +" and r <= "+range;
	System.out.println(query);
	try
	{
		Statement stmt = dbConnection.createStatement();
		ResultSet rs = stmt.executeQuery(query);
		while (rs.next())
		{
			Student student = new Student();

			student.setStudentId(rs.getInt("STUDENTID"));
			student.setName(rs.getString("NAME"));
			student.setDepartment(rs.getString("DEPARTMENT"));
			student.setEmailId(rs.getString("EMAIL"));
			students.add(student);
		}
	}
	catch (SQLException e)
	{
		System.err.println(e.getMessage());
	}
	return students;
}

 
2. As mentioned above, jTable need TotalRecordCount to be present in the json response, For which add the following function in CRUDDao which returns total Record Count value present in database.
 

public int getStudentCount()
{
	int count=0;
	try
	{
	   Statement stmt = dbConnection.createStatement();
	   ResultSet rs = stmt.executeQuery("SELECT COUNT(*) AS COUNT FROM STUDENT");
	   while (rs.next())
	   {
	 	count=rs.getInt("COUNT");
	   }
	}
	catch (SQLException e)
	{
		System.err.println(e.getMessage());
	}
	return count;
}

 

Changes made in Controller

 
The following changes where made in the logic inside the if loop -> ‘if(action.equals(“list”))’

HashMap<String, Object> JSONROOT = new HashMap<String, Object>();

if (action.equals("list")) {
	try {
	// Fetch Data from User Table
	int startPageIndex = Integer.parseInt(request.getParameter("jtStartIndex"));
	int recordsPerPage = Integer.parseInt(request.getParameter("jtPageSize"));

	// Fetch Data from Student Table
	studentList = dao.getAllStudents(startPageIndex, recordsPerPage);
	// Get Total Record Count for Pagination
	int userCount = dao.getStudentCount();

	// Return in the format required by jTable plugin
	JSONROOT.put("Result", "OK");
	JSONROOT.put("Records", studentList);
	JSONROOT.put("TotalRecordCount", userCount);

	// Convert Java Object to Json
	String jsonArray = gson.toJson(JSONROOT);

	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);
	}
}

 
Now on running the application, with the above changes, the final demo looks as shown below:
 
Pagination-Cover
 
download
 

Reference

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

Read More

CRUD Operations in Java Web Applications using jTable jQuery plugin via Ajax

Posted by in Ajax, J2EE, jQuery, jTable, Servlet | 38 comments

 
Struts-2-jTable-jQuery-plug-in-Create-record-animation-effect
 
In the previous article “Setting up JQuery jTable plugin in Java Web Applications” I have explained how to setup jTable plugin in java web application. This article describes on how to implement “Ajax based curd operation in Java Web Applications using the JQuery jTable plugin and it will not explain how to setup jTable plugin in java web application. So If you have not read the previous articles “Setting up JQuery jTable plugin in Java Web Applications I will recommend that you read that article first because it explains how you can integrate the JTable plug-in with a J2EE application, this article will assume that the code for the integration of the jQuery JTable plug-in is implemented, and only the code required for implementing CRUD operation will be explained here.
 

Steps done to set up our application for jTable

 
Libraries required for the setup,

 
Create a dynamic project in eclipse and setup above required libraries as explained here. The final project structure of this looks as below.
 
Curd in jtable java web application
 
Setup 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

 

<!DOCTYPE html>
<html>
<head>
<title>CRUD operations using jTable in J2EE</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>
<!-- User Defined Jtable js file -->
<script src="js/userDefieneJTableJs.js" type="text/javascript"></script>

</head>
<body>
<div style="text-align: center;">
	<h4>AJAX based CRUD operations using jTable in J2ee</h4>
	<div id="StudentTableContainer"></div>
</div>
</body>
</html>

 

JS File

 

$(document).ready(function() {
	$('#StudentTableContainer').jtable({
		title : 'Students List',
		actions : {
			listAction : 'Controller?action=list',
			createAction : 'Controller?action=create',
			updateAction : 'Controller?action=update',
			deleteAction : 'Controller?action=delete'
		},
		fields : {
			studentId : {
				title : 'Student Id',
				width : '30%',
				key : true,
				list : true,
				edit : false,
				create : true
			},
			name : {
				title : 'Name',
				width : '30%',
				edit : true
			},
			department : {
				title : 'Department',
				width : '30%',
				edit : true
			},
			emailId : {
				title : 'Email',
				width : '20%',
				edit : true
			}
		}
	});
	$('#StudentTableContainer').jtable('load');
});

 
I have explained the working of above jTable js file in my previous article “Setting up JQuery jTable plugin in Java Web Applications”
 
Now create a student table in Oracle database using the query below. On this table we are going to perform CRUD operation via ajax
 

create table Student(studentid int,name varchar(50),department varchar(50),
email varchar(50));

 

CurdDao

Create a class that performs CRUD operation in database
 

package com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.jdbc.DataAccessObject;
import com.model.Student;

public class CrudDao {

private Connection dbConnection;
private PreparedStatement pStmt;

public CrudDao() {
	dbConnection = DataAccessObject.getConnection();
}

public void addStudent(Student student) {
	String insertQuery = "INSERT INTO STUDENT(STUDENTID, NAME, " +
			"DEPARTMENT, EMAIL) VALUES (?,?,?,?)";
	try {
		pStmt = dbConnection.prepareStatement(insertQuery);
		pStmt.setInt(1, student.getStudentId());
		pStmt.setString(2, student.getName());
		pStmt.setString(3, student.getDepartment());
		pStmt.setString(4, student.getEmailId());
		pStmt.executeUpdate();
	} catch (SQLException e) {
		System.err.println(e.getMessage());
	}
}

public void deleteStudent(int userId) {
	String deleteQuery = "DELETE FROM STUDENT WHERE STUDENTID = ?";
	try {
		pStmt = dbConnection.prepareStatement(deleteQuery);
		pStmt.setInt(1, userId);
		pStmt.executeUpdate();
	} catch (SQLException e) {
		System.err.println(e.getMessage());
	}
}

public void updateStudent(Student student)  {
	String updateQuery = "UPDATE STUDENT SET NAME = ?, " +
			"DEPARTMENT = ?, EMAIL = ? WHERE STUDENTID = ?";
	try {
		pStmt = dbConnection.prepareStatement(updateQuery);
		pStmt.setString(1, student.getName());
		pStmt.setString(2, student.getDepartment());
		pStmt.setString(3, student.getEmailId());
		pStmt.setInt(4, student.getStudentId());
		pStmt.executeUpdate();

	} catch (SQLException e) {
		System.err.println(e.getMessage());
	}
}

public List<Student> getAllStudents() {
	List<Student> students = new ArrayList<Student>();

	String query = "SELECT * FROM STUDENT ORDER BY STUDENTID";
	try {
		Statement stmt = dbConnection.createStatement();
		ResultSet rs = stmt.executeQuery(query);
		while (rs.next()) {
			Student student = new Student();

			student.setStudentId(rs.getInt("STUDENTID"));
			student.setName(rs.getString("NAME"));
			student.setDepartment(rs.getString("DEPARTMENT"));
			student.setEmailId(rs.getString("EMAIL"));
			students.add(student);
		}
	} catch (SQLException e) {
		System.err.println(e.getMessage());
	}
	return students;
}
}

I hope the above code is self explanatory
 
Setup from the server’s perspective: Servlet
 
jTable uses the POST method by default while making AJAX calls to the server and in server side, we will convert Java objects created under different CRUD operation to JSON strings that will be parsed by jTable pugin in the JSP page and will be rendered on the web page. This conversion of Java Object to Json format is done using Google gson jar. I have used the below method of gson library to convert java object to json object
 

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonArray = gson.toJson(JSONROOT);

 
Now let us look into the different response created for CRUD operations
 

Reading

 
Method to jTable to get a list of records:
 

HashMap<String, Object> JSONROOT = new HashMap<String, Object>();

if (action.equals("list")) {
try{
	// Fetch Data from Student Table
	studentList = dao.getAllStudents();

	// 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);

	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);
}
}

 
For read operations, 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 to show in the MySql table. 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”: 1,
“name”: “Muthu vijay”,
“department”: “CSE”,
“emailId”: “[email protected]
},
{
“studentId”: 2,
“name”: “Bashit”,
“department”: “EEE”,
“emailId”: “[email protected]
},
{
“studentId”: 3,
“name”: “Haripriya”,
“department”: “IT”,
“emailId”: “[email protected]
}
]}
 

Creating & Updating

 
Creating and Updating a record is optional. If you allow user to create/update a record, you must supply an action to jTable to create a new record. In case of create you must return the newly created object in JSON format, where as in case of update you must return the updated object via its respective action, which is done via gson library. A sample return value for createAction/UpdateAction is shown below
 
{“Result”:”OK”,”Record”:{
“studentId”: 9,
“name”: “Lahir nisha”,
“department”: “CSE”,
“emailId”: “[email protected]
}}
 

if (action.equals("create") || action.equals("update")) {
try{
	Student student = new Student();
	if (request.getParameter("studentId") != null) {
		int studentId = Integer.parseInt(request.getParameter("studentId"));
		student.setStudentId(studentId);
	}

	if (request.getParameter("name") != null) {
		String name = request.getParameter("name");
		student.setName(name);
	}

	if (request.getParameter("department") != null) {
		String department = request.getParameter("department");
		student.setDepartment(department);
	}

	if (request.getParameter("emailId") != null) {
		String emailId = request.getParameter("emailId");
		student.setEmailId(emailId);
	}

	if (action.equals("create")) {
		// Create new record
		dao.addStudent(student);
	} else if (action.equals("update")) {
		// Update existing record
		dao.updateStudent(student);
	}

	// Return in the format required by jTable plugin
	JSONROOT.put("Result", "OK");
	JSONROOT.put("Record", student);

	// Convert Java Object to Json
	String jsonArray = gson.toJson(JSONROOT);
	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);
}
}

 

Deleting

 
Similar to update/create option, delete record is optional. If you allow user to delete a record, you must supply an action to jTable to delete a record, and response of delete operation is similar to update.
 

if (action.equals("delete")) {
try{
	// Delete record
	if (request.getParameter("studentId") != null) {
		int studentId = Integer.parseInt(request.getParameter("studentId"));
		dao.deleteStudent(studentId);

		// Return in the format required by jTable plugin
		JSONROOT.put("Result", "OK");

		// Convert Java Object to Json
		String jsonArray = gson.toJson(JSONROOT);
		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);
}
}

 

Model class

 
Create Model class used in the controller, which will have getters and setters for fields specified in jTable script.

package com.model;

public class Student {

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

 

DAO Class

 
Create utility class which connect to database Using Oracle JDBC driver

package com.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;

public class DataAccessObject {
	private static Connection connection = null;

	public static Connection getConnection() {
		if (connection != null)
			return connection;
		else {
			// Store the database URL in a string
		String serverName = "127.0.0.1";
		String portNumber = "1521";
		String sid = "XE";
		String dbUrl = "jdbc:oracle:thin:@" + serverName + ":" + portNumber
				+ ":" + sid;
		try {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		// set the url, username and password for the database
		connection = DriverManager.getConnection(dbUrl, "system", "admin");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}
	}
}

 

web.xml

 

<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

 
On running the application
 
Integrating-jQuery-jTable-plugin-with-Struts2-framework
 
On clicking ‘Add new record’
Struts-2-using-jTable-jQuery-plug-in-Create-record
 
Now the new record will be added with fade out animation
Struts-2-jTable-jQuery-plug-in-Create-record-animation-effect
 
On clicking edit button
Struts-2-jTable-jQuery-plug-in-Update-record
 
On clicking delete button
Struts-2-jTable-jQuery-plug-in-Delete-record
 
In the next article Pagination in Java Web Applications using jQuery jTable plugin I have implemented paging feature to the CRUD example demonstrated here.
 
download
 

Reference

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

Read More

Setting up jQuery jTable plugin in Servlets and JSP

Posted by in J2EE, Java, jQuery, jTable | 6 comments

 
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", "[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,
 

<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
 

Read More

Setting up jQuery jTable plugin in Struts 2 framework

Posted by in jQuery, jTable, Struts 2 Tutorial, Struts-2 | 42 comments

 
In this article we will learn to setup jTable and dependent libraries in Struts 2 web application. jTable is a jQuery plugin which is used to create AJAX based CRUD tables without coding HTML or Javascript, to know more about jTable please refer the article here
 

Steps done to set up our application for jTable

 
Libraries required for the setup,

 
Now to start with demonstration of above topic, let us Create a Dynamic Web Project in Eclipse, with following project structure.
 
jTable in struts 2
 
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

 
File : jTable.jsp

<html>
<head>
<title>jTable in Struts 2</title>
<!-- jTable Metro theme -->
<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 : 'listAction'
			},
			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>
	<h3>Integrating jTable jQuery plugin and Struts 2 framework</h3>
	    <div id="StudentTableContainer"></div>
</div>
</body>
</html>

 
As you can see, jTable just needs a div container 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.
 
Setup done from the server’s perspective: Struts 2 Action class
 
In the Action class, we are populating a list of type “Student”(Model). Since jTable accepts data only in Json format, so we are converting this List (Java Object) to Json(Javascript object Notation) format using struts2-json-plugin.jar.

**Update:: In the article AJAX implementation in Struts 2 using JQuery and JSON I have explained about usage of struts2-json-plugin.jar clearly, So if you are not aware of how struts2-json-plugin works, then please go thorough the above mentiioned link.

 

Action Class

 

package com.simplecodestuffs.action;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.Action;
import com.simplecodestuffs.model.Student;

public class JtableAction {

	private List<Student> records = new ArrayList<Student>();
	private String result;

	public String list() {
		// Add data to Student list
		records.add(new Student(1, "Haripriya", "IT", "[email protected]"));
		records.add(new Student(2, "Dinesh", "ECE", "[email protected]"));
		records.add(new Student(3, "Prabhu", "MECH", "[email protected]"));
		records.add(new Student(4, "Badru", "ECE", "[email protected]"));
		records.add(new Student(5, "Lahir nisha", "CSC", "[email protected]"));
		records.add(new Student(6, "Nilafar nisha", "CSC", "[email protected]"));
		records.add(new Student(7, "Jamil", "ECE", "[email protected]"));
		records.add(new Student(8, "Mahes", "ECE", "[email protected]"));
		records.add(new Student(9, "Lourde", "IT", "[email protected]"));
		result = "OK";

		return Action.SUCCESS;
	}

	public List<Student> getRecords() {
		return records;
	}

	public void setRecords(List<Student> records) {
		this.records = records;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}
}

 
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 action class. 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":1,
"name":"Haripriya",
"department":"IT",
"emailId":"[email protected]"
}]
}

 

Model Class

 
Create the Model class which will have getters and setters for fields specified in jTable script.
 

package com.simplecodestuffs.model;

public class Student {

	public Student() {
	}

	public Student(int studentId, String name, String department, String emailId) {
		super();
		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;
	}
}

 

Struts.xml

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="json-default">
   <action name="listAction" class="com.simplecodestuffs.action.JtableAction"
	method="list">
	<result type="json">/jTable.jsp</result>
  </action>
  <action name="getJSONResult" class="com.simplecodestuffs.action.JtableAction" method="list">
	<result type="json" />
  </action>
</package>
</struts>

Since jTable accepts data only in Json format, So in order to convert java object to json object I have extended json-default package instead of struts-default package, please refer article here for more detail on json-default package.
 

Demo

 
On running the application i got the following response
 
Jtable exception
 
Since I have not handled any exception, so the message displayed in error box is empty.
 
While debugging the error I found that the json response formed in struts application as below.
get json result in Jtable
 
Hear the property names of jTable plugin are case sensitive. Only “Result”, “Records” and “Message” will work. In struts 2 the “json response” generated is in lower case[“result”, “records” and “message”], hence I edited the jtable.js to replace Result to result, Records to records and Message to message then it worked.
 
**Note: Along with the above keyword replace TotalRecordCount to totalRecordCount respectively, since this parameter will be used to display pagination count(Which I will implement in upcoming tutorial)
 
jquery-jtable-in-struts-2
 
Now on including action for create, update and delete in jsp page as below

actions : {
	listAction : 'list',
	createAction : 'create',
	updateAction : 'update',
	deleteAction : 'delete'
}

 
On running the application
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. In the article CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax I have implemented CRUD operation using jTable jQuery plugin in Struts 2, and in the article Pagination in Struts 2 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
 

Read More