Setup and Load Data in jQGrid using Servlets and JSP
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.
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
jqGird in Servlet
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"); ListjqGridModels = 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.
GridServlet servlet.JqGridServlet GridServlet /GridServlet index.jsp
Demo
On running the application
On clicking add icon
On clicking edit icon
** 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.
will this stuff works in netbeans
com.google.gson.Gson;
com.google.gson.GsonBuilder;
it shows it doesnt exist how to rectify it even after including mentioned jar files
i developed the jqgrid working fine with data base data.but if i use this jqgrid in another page it is not showing the grid….can anyone answer to my problem…..
Hi Jamil,
I have some queries:-
1.) if I put a simple code to alert some text in the “getJqGridData.js” file it won’t work
(inspite of giving the jQuery CDN path) . Why??
2.)if I want a functionality , to have the table displayed only on the click of a button ,what should be done.
Thanks
thanks for sharing.. nice tutorial
are you sure about showing total as 2, where total is number of pages here it is shown as 2 for just 2 records…is this correct ?
Hi thanks for pointing it out. Here the attribute “total” holds number of page values.
It should be determined at the server side by dividing “Total no of Records”/”No of records per page”. Hope you got cleared.
yup..thanks :)
[code] $(“#sendAll1”).click(function(){
alert(“send”);
//var localGridData = $(“#list”).jqGrid(‘getGridParam’,’data’);
// alert(“”+localGridData);
var data = $(“#list”).jqGrid(“getRowData”);
alert(“ankita”+data);
var dataToSend = JSON.stringify(data);
alert(“The following data are sending to the server:\n” + dataToSend);
$.ajax({
type: “POST”,
url: “savedoctor1″,
dataType:”json”,
data: dataToSend,
contentType: “application/json; charset=utf-8”,
success: function(response, textStatus, jqXHR ,data) {
// display an success message if needed
alert(“success”);
},
error: function(jqXHR, textStatus, errorThrown) {
// display an error message in any way
alert(“error”);
}
});
});
[/code]
i want able how to receive at servlet
you site is really helpful plz upload the above code thanks in advance.
Hi I have Uploaded the source code
Hi Jameel,
The import for :
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
is showing cannot be resolved. All Jars included already as suggested.
Please clean and build your project
Hola una consulta, en “url:” que pones exactamente? he visto que algunos ponen algo asi: unapagina.jsp y otros ponen algo asi: “LoadJsonDataServlet?type=BS21 7RH”… me podrias explicar esto porfa.
gracias
Hola ,
Me olvidé de incluir archivos web.xml configurtion en el puesto. Ahora he puesto al día . La configuración para GridServlet se puede encontrar en el mismo.
Insert title here
alert(“hellodhjfgfs”);
alert(“bnx bhyy”);
var data = [[48803, “DSK1”, “”, “02200220”, “OPEN”], [48769, “APPR”, “”, “77733337”, “ENTERED”]];
alert(“bnx1”);
$(“#grid”).jqGrid({
datatype: “local”,
height: 250,
colNames: [‘Inv No’, ‘Thingy’, ‘Blank’, ‘Number’, ‘Status’],
colModel: [{
name: ‘id’,
index: ‘id’,
width: 60,
sorttype: “int”},
{
name: ‘thingy’,
index: ‘thingy’,
width: 90,
sorttype: “date”},
{
name: ‘blank’,
index: ‘blank’,
width: 30},
{
name: ‘number’,
index: ‘number’,
width: 80,
sorttype: “float”},
{
name: ‘status’,
index: ‘status’,
width: 80,
sorttype: “float”}
],
caption: “Stack Overflow Example”
// ondblClickRow: function(rowid,iRow,iCol,e){alert(‘double clicked’);}
});
alert(“1st”);
var names = [“id”, “thingy”, “blank”, “number”, “status”];
var mydata = [];
for (var i = 0; i < data.length; i++) {
mydata[i] = {};
for (var j = 0; j < data[i].length; j++) {
mydata[i][names[j]] = data[i][j];
}
}
for (var i = 0; i <= mydata.length; i++) {
$("#grid").jqGrid('addRowData', i + 1, mydata[i]);
alert("2nd");
}
/*
$("#grid").jqGrid('setGridParam', {onSelectRow: function(rowid,iRow,iCol,e){alert('row clicked');}});
*/
$("#grid").jqGrid('setGridParam', {ondblClickRow: function(rowid,iRow,iCol,e){alert('double clicked');}});
kam cho?
what is problem in this code?
hi,
insertion of data is not happenign please help me out
Hi,
This is just a sample application to setup jQgrid. I have not written any logic for CRUD operations