jqGrid + Servlet

Hello all, one of my fiend has a requirement to generate a data grid model so, we thought directly using jqGrid component here is my tutorial which will populate data in grid format.
Step 1: jqGrid will call servlet using an Ajax call.
Step 2: Servlet returns data in the form of JSON.
Step 3: jqGrid Component will parse JSON data from servlet and render it in the component.
Step 4: giving additional functionality as “add,edit,delete” directly to jqGrid component.
prj_structure

lets start looking at the logic
GridServlet.java

package com.spark.javaee.servlets;

import java.io.IOException;
import java.io.PrintWriter;
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 net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

/**
 * Servlet implementation class LoginServlet
 */
public class GridServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		GridModel gridModel1 = new GridModel();
		gridModel1.setId(1);
		gridModel1.setFirstName("PavanKumar");
		gridModel1.setLastName("Mantha");
		gridModel1.setCity("Hyderabad");
		gridModel1.setState("AndhraPradesh");
		gridModel1.setPhoneNumber("1234567890");
		
		GridModel gridModel2 = new GridModel();
		gridModel2.setId(2);
		gridModel2.setFirstName("PavanKumar");
		gridModel2.setLastName("Mantha");
		gridModel2.setCity("Hyderabad");
		gridModel2.setState("AndhraPradesh");
		gridModel2.setPhoneNumber("1234567890");
		
		List<GridModel> gridModels = new ArrayList<>();
		gridModels.add(gridModel1);
		gridModels.add(gridModel2);
		
		JSONArray jsonArray = (JSONArray)JSONSerializer.toJSON(gridModels);
		String json = "{'page':1,'total':'2','records':'1','rows':"+jsonArray+"}";
		JSONObject jsonObject = (JSONObject)JSONSerializer.toJSON(json);
		
		PrintWriter out = response.getWriter();
		out.print(jsonObject.toString());
	}

}

Lets look at the model class
GridModel.java

/**
 * 
 */
package com.spark.javaee.servlets;

import java.io.Serializable;

/**
 * @author Sony
 * 
 */
public class GridModel implements Serializable {

	private int id;
	private String firstName;
	private String lastName;
	private String city;
	private String State;
	private String phoneNumber;

	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}

	/**
	 * @return the firstName
	 */
	public String getFirstName() {
		return firstName;
	}

	/**
	 * @param firstName
	 *            the firstName to set
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	/**
	 * @return the lastName
	 */
	public String getLastName() {
		return lastName;
	}

	/**
	 * @param lastName
	 *            the lastName to set
	 */
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	/**
	 * @return the city
	 */
	public String getCity() {
		return city;
	}

	/**
	 * @param city
	 *            the city to set
	 */
	public void setCity(String city) {
		this.city = city;
	}

	/**
	 * @return the state
	 */
	public String getState() {
		return State;
	}

	/**
	 * @param state
	 *            the state to set
	 */
	public void setState(String state) {
		State = state;
	}

	/**
	 * @return the phoneNumber
	 */
	public String getPhoneNumber() {
		return phoneNumber;
	}

	/**
	 * @param phoneNumber
	 *            the phoneNumber to set
	 */
	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

}

now its time to look at jsp

<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!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>jqGird Demo</title>
<link rel="stylesheet"
	href="assets/themes/redmond/jquery.ui.all.css">

<script src="assets/js/jquery-1.8.0.min.js"></script>
<script src="assets/ui/jquery.ui.core.js"></script>
<script src="assets/ui/jquery.ui.widget.js"></script>
<script src="assets/ui/jquery.ui.datepicker.js"></script>
<script src="assets/js/grid.locale-en.js"></script>
<script src="assets/js/jquery.jqGrid.src.js"></script>
<script src="assets/js/jquery-ui-1.8.23.custom.min.js"></script>
<script src="assets/js/json2.js"></script>


<link rel="stylesheet" href="assets/demos.css">
<link rel="stylesheet" href="assets/ui.jqgrid.css">
<script src="js/getGridData.js"></script>
</head>
<body>
	<table id="list">
		<tr>
			<td />
		</tr>
	</table>
	<div id="pager"></div>
</body>
</html>

lets look at the javascript

/**
 * Code for JQuery Grid.
 */
$(document)
		.ready(
				function() {
					$("#list")
							.jqGrid(
									{
										url : 'http://localhost:8080/JQueryTest/GridServlet',
										datatype : 'json',
										mtype : 'POST',
										colNames : [ 'id', 'firstName',
												'lastName', 'city', 'state',
												'phoneNumber' ],
										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 : 80,
											editable : true
										}, {
											name : 'state',
											index : 'state',
											width : 100,
											editable : true
										}, {
											name : 'phoneNumber',
											index : 'phoneNumber',
											width : 80,
											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 : "http://localhost:8080/JQueryTest/GridServlet"
									});
					jQuery("#list").jqGrid('navGrid', '#pager', {
						edit : true,
						add : true,
						del : true,
						search : true
					});
				});


This is how the result looks by loading data
load

This is how the result looks after clicking add button and the request:
request

This is how the result looks after clicking edit button and the request:
edit

Happy Coding 🙂

Advertisements