Pages Navigation Menu

Coding is much easier than you think

Pagination in Java Web Applications using jQuery jTable plugin

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

 
pagination in j2ee
 
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 and in the article “Ajax based CRUD operation in Java Web Applications using JQuery jTables plugin” I have implemented Ajax based CRUD operation using JTable plugin.
 
This is the third article on jQuery jTable plugin in java web application that describes on how to implement pagination feature to do server side paging and it will not explain how to setup jTable plugin in java web application here. So If you have not read the 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 plug-in with a Java web application and in second article explains on how to implement ajax based curd operation using jTable plugin. 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 pagination in Java web application using jTable will be explained here.
 

Setup

 
As described above, the prerequisite for this code is that you integrate the jQuery jTable plugin into the Java web application. You can find detailed instructions at JQuery jTable plugin in Java web application, so now I am going to take the sample application I created for explaining AJAX based crud operations in jTable plugin and continue to implement paging for that application.
 
1. Download sample application from here and import the project in eclipse.
2. Follow the steps in this article here to create table in database and make sure you have atleast 5 records in the table.
 
Now on running this application in Tomcat Server, you will see a table displaying records without pagination such as the one shown below.
 

 

Steps to Enable Paging:

 

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

 
Now open ‘CRUDContoller.java’ file and replace the logic inside the if loop -> ‘if(action.equals(“list”))’ with the below code,

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

	// Return Json in the format required by jTable plugin
	jsonArray = "{\"Result\":\"OK\",\"Records\":" + jsonArray
			+ ",\"TotalRecordCount\":" + userCount + "}";
	response.getWriter().print(jsonArray);
	}
	catch(Exception ex){
		String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getMessage()+"}";
		response.getWriter().print(error);
}
}

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


  Read More

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

Posted by in Ajax, J2EE, jQuery, jTable, Servlet

 
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 pagination in Java web application using jTable 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

 

<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”, hence I’m not going to explain it again.
 
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(studentList);

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

Reading

 
Method to jTable to get a list of records:
 

if (action.equals("list")) {
try {
	// Fetch Data from Student Table
	studentList = dao.getAllStudents();
	// Convert Java Object to Json
	String jsonArray = gson.toJson(studentList);

	// Return Json in the format required by jTable plugin
	jsonArray = "{\"Result\":\"OK\",\"Records\":"+ jsonArray + "}";
	response.getWriter().print(jsonArray);
	} catch (Exception e) {
		String error = "{\"Result\":\"ERROR\",\"Message\":" + e.getMessage()+ "}";
		response.getWriter().print(error);
		System.err.println(e.getMessage());
	}
}
catch (Exception e) {
	String error = "{\"Result\":\"ERROR\",\"Message\":"
		+ "Exception on listing records }";
	response.getWriter().print(error);
	System.err.println(e.getMessage());
	}
}

 
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

 
Creating a record is optional. If you allow user to create a record, you must supply an action to jTable to create a new record. This method must return the newly created object in JSON format, which is done via gson library. A sample return value for createAction is shown below
 
{“Result”:”OK”,”Record”:{
“studentId”: 9,
“name”: “Lahir nisha”,
“department”: “CSE”,
“emailId”: “[email protected]
}}
 

if (action.equals("create")) {
		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);
		}

		try {
			// Create new record
			dao.addStudent(student);
			// Convert Java Object to Json
			String json = gson.toJson(student);
			// Return Json in the format required by jTable plugin
			String jsonData = "{\"Result\":\"OK\",\"Record\":"+ json + "}";
			response.getWriter().print(jsonData);
		} catch (Exception e) {
			String error = "{\"Result\":\"ERROR\",\"Message\":" + e.getMessage()+ "}";
			response.getWriter().print(error);
		}
}

 

Updating

 
Update a record is optional. If you allow user to edit (update) a record, then you must supply an action to jTable to update a record, here if update option is successful, then, Result property must be “OK”. If error then Result property must be “ERROR”.
 

if (action.equals("update")) {
		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);
		}

		try {
			// Update existing record
			dao.updateStudent(student);
			// Convert Java Object to Json
			String json = gson.toJson(student);
			String jsonData = "{\"Result\":\"OK\",\"Record\":" + json + "}";
			response.getWriter().print(jsonData);
		} catch (Exception e) {
			String error = "{\"Result\":\"ERROR\",\"Message\":" + e.getMessage()+ "}";
			response.getWriter().print(error);
		}
	}

 

Deleting

 
Similar to update 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);
			String jsonData = "{\"Result\":\"OK\"}";
			response.getWriter().print(jsonData);
		}
	} catch (Exception e) {
		String error = "{\"Result\":\"ERROR\",\"Message\":" + e.getMessage()+ "}";
		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.
 

dwd2
Download It – AjaxjTableServlet.war

 

Reference

 
http://www.codeproject.com/Articles/277576/AJAX-based-CRUD-tables-using-ASP-NET-MVC-and-jTa

Read More

Setting up jQuery jTable plugin in Servlets and JSP

Posted by in J2EE, Java, jQuery, jTable

 
In this article we will learn to setup jTable and dependent libraries in a Java web application(using Servlets and JSP’s)
 
Integrating jQuery jTable plugin with Struts2 framework
 
As per the definition in jTable.org, jTable is a jQuery plugin which is used to create AJAX based CRUD tables without coding HTML or Javascript. jTable takes a div id and automatically generates the html table inside the div and it uses jQuery UI dialog that pops up when the user clicks on add, edit or update record buttons and it has several pre-defined color themes . In this example I have used metro blue theme for my project.

To know more on jTable plugin please read on its official home page.
 

Steps done to set up our application for jTable

 
Libraries required
jquery plugin

 
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 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>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 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.
 
In the jsp above I have only provided action url for listAction for demonstration purpose. 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.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;

    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]"));

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

		//Return Json in the format required by jTable plugin
		jsonArray="{\"Result\":\"OK\",\"Records\":"+jsonArray+"}";
		System.out.println(jsonArray);
		response.getWriter().print(jsonArray);
		}
		catch(Exception ex){
			String error="{\"Result\":\"ERROR\",\"Message\":"+ex.getMessage()+"}";
			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'
}

 
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 Java Web Applications using jTable jQuery plugin via Ajax I have implemented CRUD operation using jTable jQuery plugin in J2EE, and in the article Pagination in Java Web Applications using jQuery jTable plugin I have implemented paging feature using the same plugin.
 

dwd2
Download It – jTableInServlet

 

Reference

 
http://jtable.org/ApiReference
 

Read More

Setting up jQuery jTable plugin in Struts 2 framework

Posted by in jQuery, jTable, Struts 2 Tutorial, Struts-2 | 18 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 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":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.
 

dwd2
Download It – jTableInStruts2

 

Reference

 
http://jtable.org/ApiReference
 

Read More
SimpleCodeStuffs located at , India, Chennai . Reviewed by rated: 8.8 / 10