Pages Navigation Menu

Coding is much easier than you think

Setup and Load Data in jQGrid using Servlets and JSP

Posted by on Aug 27, 2014 in Ajax, jQuery | 18 comments

JqGrid is an Ajax-enabled JavaScript control that provides solutions for representing and manipulating grid data on the web. Since the grid loads data at client side via Ajax call-backs, so it can be integrated with any server-side technology, including PHP, ASP and Java. JqGrid uses a jQuery Java Script Library and is written as plugin for that package.
 

Library required

 
JqGrid library
Jquery UI theme
google-gson-2.2.4.jar
 
Now to start with demonstration of above topic, let us Create a Dynamic Web Project in Eclipse, with following project structure.
 
JqGrid structure
 
As show in the image download the required library mentioned and place it in jQGrid and gridJs 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: JqGrid
 
jQGrid 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>jqGird in Servlet</title>

<link rel="stylesheet" href="jqueryJs/jquery-ui.css">
<link rel="stylesheet" href="gridJs/css/ui.jqgrid.css">

<script src="jqueryJs/external/jquery/jquery.js"></script>
<script src="gridJs/js/i18n/grid.locale-en.js"></script>
<script src="gridJs/js/jquery.jqGrid.src.js"></script>
<script src="jqueryJs/jquery-ui.js"></script>

<script src="js/getJqGridData.js"></script>

</head>
<body>
	<table id="list">
		<tr>
			<td />
		</tr>
	</table>
	<div id="pager"></div>
</body>
</html>

 
As you can see, jQGrid just needs a div and table element as HTML tags.
 
You might be interested to read:

 

JS File

 
File : getJqGridData.js

jQuery(document).ready(function() {
	$("#list").jqGrid({
		url : "GridServlet",
		datatype : "json",
		mtype : 'POST',
		colNames : [ 'Id', 'FirstName', 'LastName', 'City', 'State' ],
		colModel : [ {
			name : 'id',
			index : 'id',
			width : 100
		}, {
			name : 'firstName',
			index : 'firstName',
			width : 150,
			editable : true
		}, {
			name : 'lastName',
			index : 'lastName',
			width : 150,
			editable : true
		}, {
			name : 'city',
			index : 'city',
			width : 100,
			editable : true
		}, {
			name : 'state',
			index : 'state',
			width : 100,
			editable : true
		} ],
		pager : '#pager',
		rowNum : 10,
		rowList : [ 10, 20, 30 ],
		sortname : 'invid',
		sortorder : 'desc',
		viewrecords : true,
		gridview : true,
		caption : 'Data Report',
		jsonReader : {
			repeatitems : false,
		},
		editurl : "GridServlet"
	});
	jQuery("#list").jqGrid('navGrid', '#pager', {
		edit : true,
		add : true,
		del : true,
		search : true
	});
});

 
Setup done from the server’s perspective: Servlet
 
In Servlet, we are going to use a JSON library to convert Java objects(jqGridModels) to JSON strings that will be parsed by jQGrid plugin 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.
 

Servlet

 

package 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 model.JqGridModel;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

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

	protected void doPost(HttpServletRequest request,
		    HttpServletResponse response) throws ServletException, IOException {

		JqGridModel gridModel1 = new JqGridModel();
		gridModel1.setId(1);
		gridModel1.setFirstName("Mohaideen");
		gridModel1.setLastName("Jamil");
		gridModel1.setCity("Coimbatore");
		gridModel1.setState("TamilNadu");

		JqGridModel gridModel2 = new JqGridModel();
		gridModel2.setId(2);
		gridModel2.setFirstName("Ameerkhan");
		gridModel2.setLastName("Saffar");
		gridModel2.setCity("Thirunelveli");
		gridModel2.setState("Tamilnadu");

		List<JqGridModel> jqGridModels = new ArrayList<>();
		jqGridModels.add(gridModel1);
		jqGridModels.add(gridModel2);

		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		String jsonArray = gson.toJson(jqGridModels);
		jsonArray = "{\"page\":1,\"total\":\"2\",\"records\":"
			+ jqGridModels.size() + ",\"rows\":" + jsonArray + "}";

		System.out.println(jsonArray);

		response.getWriter().print(jsonArray);
	}
}

 
For jQGrid, page property represents current page number, and total represent total no pages, records represents Total number of records and rows represent the actual data. A sample return value from the above servlet is shown below
 
{“page”:1,”total”:”2″,”records”:2,”rows”:[
{
“id”: 1,
“firstName”: “Mohaideen”,
“lastName”: “Jamil”,
“city”: “Coimbatore”,
“state”: “TamilNadu”
},
{
“id”: 2,
“firstName”: “Ameerkhan”,
“lastName”: “Saffar”,
“city”: “Thirunelveli”,
“state”: “Tamilnadu”
}
]}
 

Model class

 
Create the Model class , which will have getters and setters for fields used in js file

package model;

public class JqGridModel {

	private int id;
	private String firstName;
	private String lastName;
	private String city;
	private String state;

	public int getId() {
		return id;
	}

	public String getFirstName() {
		return firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public String getCity() {
		return city;
	}

	public String getState() {
		return state;
	}

	public void setId(int id) {
		this.id = id;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public void setState(String state) {
		this.state = state;
	}
}

 

web.xml

 
Make sure that the web.xml has the following mapping.

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

 

Demo

 
On running the application
Demo JqGrid
 
On clicking add icon
jQGrid add
 
On clicking edit icon
eDit JqGrid
 
** Update — The below screenshot is the demo of pagination in java web application via ajax using using jQuery jTable plugin, this plugin has several inbuilt theme and lot may cool features like crud implementation via ajax, internalization etc, to know more about this plugin, please refer the article here.
 
Pagination-Cover
 
download
 

Read More