Pages Navigation Menu

Coding is much easier than you think

Pagination in Servlet and JSP using jQuery jTable plugin

Posted by on Sep 30, 2014 in Ajax, J2EE, jQuery, jTable, Servlet | 8 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

Servlet + Jsp Hello World Example

Posted by on Jun 15, 2013 in JSP, Servlet | 1 comment

 
In our previous tutorial we got introduced to what a JSP is, In this article we are going to cover how to write Hello world example using both Servlet and Jsp.
 

Final Project Structure

 
Hello world using Servlet and  jsp
 

Servlet

 

package com.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorldServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		RequestDispatcher rd = request.getRequestDispatcher("hello.jsp");
		rd.forward(request, response);
	}
}

 

web.xml

 
Make sure that your web.xml file has following mapping

<web-app ..>
	<display-name>HelloWorldServlet</display-name>
	<servlet>
		<servlet-name>HelloWorld</servlet-name>
		<servlet-class>com.servlet.HelloWorldServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>HelloWorld</servlet-name>
		<url-pattern>/helloworld</url-pattern>
	</servlet-mapping>
</web-app>

 

JSP Page

 

<html>
<head>
<title>Hello world in Servlet + JSP</title>
</head>
<body>
	<p>Hurray!! This Servlet worked!!!</p>
</body>
</html>

 

Demo

Deploy the application tomcat server and enter the URL to access HelloWorldServlet “http://localhost:8089/HelloWorldServlet/helloworld”
 
Run hello world servlet  JSP
 

Read More

Why use JSP when we can do the same thing with servlets?

Posted by on Jun 10, 2013 in J2EE, JSP, Servlet | 0 comments

Highly Coupled Servlets

 
In our previous tutorial we have implemented an servlet hello world example, in which a servlet acts as both controller as well as presenter; below are the list of problem when servlet acts as both controller and presenter,

  • High cost of maintenance
  • HTML and Java exist in the same file.
  • Web Designers don’t understand java code, don’t like the java code…
  • Programmers don’t particularly like the messing with <HTML> code!!!!

 
In simple words ….

if( developer == javaProgrammer)
	System.out.println("Stick to Java code!");
else if( developer == webDesigner )
        System.out.println("Stick to html code!");

 
So its better to separate JAVA code from the HTML code. Now the Question is How to Separate ????
 

Java Server Pages(JSP)

 
Java Server Pages (JSPs) provide a way to separate the generation of dynamic content (java) from its presentation (html)
 

How do JSP’s Work

 
The work flow of jsp is depicted pictographically below.
 
jsp work flow
 
In our next tutorial we shall learn to implement hello world example in servlet using JSP.
 

Read More

Introduction to Java web application & Servlets

Posted by on May 28, 2013 in J2EE, JSP, Servlet | 0 comments

 
In this article let’s us learn about how the communication happens in a web world.
client-server-architecture
 

Client: In case of web application, web browser acts as client through which a user sends a request to server.
 
Server: A server is a combination of a hardware machines and a number of software’s running on that machine. The duty of server is to serve resources that are being requested by the client.

 
Note:
Servers itself are capable of serving static resources only.
 

HTTP Protocol

Inorder to communicate between client and server we need some set of rules so called http (Hyper text transfer protocol). In web there are a number of protocols other than http that does the communication work done, but almost in 99% of applications the requests being made are http requests.

Http: Http can be assumed as a common interface of interaction that both client and server understand.

 
Note
HTTP is a stateless protocol i.e. HTTP supports only one request per connection. This means that with HTTP the clients connects to the server to send one request and then disconnects. This mechanism allows more users to connect to a given server over a period of time.
 

Request/Response cycle

 
Web flow starts when a request is made by user via browser (client), this request is made as http request so that server can understand it. The server receives the request, finds the resources and return response to the client in form of HTTP. When a server answers a request the server usually sends some type of content to the client. The server often sends responds to the browser with a set of instructions written in HTML (HyperText Markup Language). All browsers know how to display HTML page to the user.
 

Http Request: Http requests basically have three major components.
1 – HTTP method, there are 7 methods defined in java servlets but most of the time you will see either a get or post method.
2 – The requested page URL, the page to access like www.fb.com.
3 – Parameters, parameters (as userName, password… etc.) are being send as part of request on which the response is being generated.
 
Http Response: Http requests basically have three major components.
1 – A status code, this code tells the browser whether the request is successful or not.
2 – Content type, it tells the browser about the type of content that response web page contains in it (text, picture, html…etc).
3 – The content is the information that is served as response that the user was requested.
 
So far we are familiar with the request-response cycle and client-server model over the web.
 

So here, where the Servlet does come into the picture?

 
Let’s assume a user requests a page having some text information written on some topic. This page content is never going to change and the same page is sent back to every user request.

But if a user requests to access his facebook account, this time server needs to create a page of that user’s information based on username and password provided by the user. Here the username and password are called parameters and the response is being generated dynamically based on user’s request parameter are called dynamic pages.
 
As I said before that the server can serve only static pages as response, so in case if we need to serve dynamic pages then server must have something that provides dynamic contents to serve and this can be done via servlets. Servlets are nothing but helper applications that helps the server to response back dynamic pages.
 
We shall learn about how these servlets helps server in serving dynamic contents in our upcoming tutorials. In our next article we shall learn about Servlet Architecture.
 

Read More

How to Reload a Page Only Once Using Javascript

Posted by on Mar 14, 2013 in JSP | 3 comments

 
This code snippet allows reloading a page only once. It will be helpful to prevent some data being cached.
 

<script language="JavaScript" type="text/javascript">
var reload = false;
var loc=""+document.location;
loc = loc.indexOf("?reload=")!=-1?loc.substring(loc.indexOf("?reload=")+10,loc.length):"";
loc = loc.indexOf("&")!=-1?loc.substring(0,loc.indexOf("&")):loc;
reload = loc!=""?(loc=="true"):reload;

function reloadPage() {
    if (!reload) 
        window.location.replace(window.location+"?reload=true");
}
//You can call this via the body tag if desired
reloadPage(); 
</script>

 
Another must read

 

Read More