Introduction
jqGrid is an Ajax-enabled JavaScript control that provides solutions for representing and manipulating tabular data on the web. Since the grid is a client-side solution loading data dynamically through Ajax callbacks, it can be integrated with any server-side technology, including PHP, ASP, Java Servlets, JSP, ColdFusion, and Perl.jqGrid uses a jQuery Java Script Library and is written as plugin for that package. For more information on jQuery, please refer to the jQuery web site.
Example
Structure of Dynamic Web Application
JqGridData.java
package com.demo; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.simple.JSONValue; public class JqGridData<T> { /** Total number of pages */ private int total; /** The current page number */ private int page; /** Total number of records */ private int records; /** The actual data */ private List<T> rows; public JqGridData(int total, int page, int records, List<T> rows) { this.total = total; this.page = page; this.records = records; this.rows = rows; } public int getTotal() { return total; } public int getPage() { return page; } public int getRecords() { return records; } public List<T> getRows() { return rows; } public String getJsonString(){ Map<String, Object> map = new HashMap<String, Object>(); map.put("page", page); map.put("total", total); map.put("records", records); map.put("rows", rows); return JSONValue.toJSONString(map); } }
Person.java
package com.demo; public class Person { private String firstName; private String lastName; private String address; public Person(String firstName, String lastName, String address) { this.firstName = firstName; this.lastName = lastName; this.address = address; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String toString() { return "{\"firstName\":\"" + firstName + "\", \"lastName\":\"" + lastName + "\", \"address\":\"" + address + "\"}"; } }
Data.java
package com.demo; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Data { private static Map<String, List<Person>> data = new HashMap<String, List<Person>>(); static{ populateBS217RHData(); populateBS18QTData(); } public List<Person> getData(String postcode){ return data.get(postcode.toUpperCase()); } private static void populateBS217RHData(){ List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Adam", "Davies", "18 Knowles Road Clevedon")); personList.add(new Person("David", "Smith", "185 Old Kent Road, Clevedon")); personList.add(new Person("Jane", "Adams", "216 Park Road, Clevedon")); personList.add(new Person("Sue", "Green", "207 Old Stree, Clevedon")); data.put("BS21 7RH", personList); } private static void populateBS18QTData(){ List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Sarah", "Jones", "1354 Ashley Road, Bristol")); personList.add(new Person("Jayne", "Peters", "254 ALma Vale Road, Bristol")); personList.add(new Person("Peter", "Richards", "Flat 4, 567 Clifton Road, Bristol")); personList.add(new Person("Andrew", "Love", "324 Regent Street, Bristol")); data.put("BS1 8QT", personList); } }
LoadJsonDataServlet.java
package com.demo; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.simple.JSONValue; public class LoadJsonDataServlet extends HttpServlet { private static final long serialVersionUID = 1L; public LoadJsonDataServlet() { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String postcode = request.getParameter("type") ; if(postcode == null || postcode.trim().length() == 0) postcode = "BS21 7RH"; System.out.println("Type: " + postcode); List<Person> personList = new Data().getData(postcode); int totalNumberOfPages = 1; int currentPageNumber = 1; int totalNumberOfRecords = 8; // All in there are 8 records in our dummy data object JqGridData<Person> gridData = new JqGridData<Person>(totalNumberOfPages, currentPageNumber, totalNumberOfRecords, personList); System.out.println("Grid Data: " + gridData.getJsonString()); response.getWriter().write(gridData.getJsonString()); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
index.html
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>jqGrid Example</title> <script type='text/javascript' src='http://code.jquery.com/jquery-1.6.2.js'></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.js"></script> <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/base/jquery-ui.css"> <link rel="stylesheet" type="text/css" href="http://trirand.com/blog/jqgrid/themes/ui.jqgrid.css"> <script type='text/javascript' src="http://trirand.com/blog/jqgrid/js/i18n/grid.locale-en.js"></script> <script type='text/javascript' src="http://trirand.com/blog/jqgrid/js/jquery.jqGrid.min.js"></script> <style type='text/css'> </style> <script type='text/javascript'>//<![CDATA[ $(window).load(function(){ var data = [[48803, "DSK1", "", "02200220", "OPEN1"], [48769, "APPR", "", "77733337", "ENTERED1"]]; $("#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: "Static Data Example", // ondblClickRow: function(rowid,iRow,iCol,e){alert('double clicked');} }); 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]); } /* $("#grid").jqGrid('setGridParam', {onSelectRow: function(rowid,iRow,iCol,e){alert('row clicked');}}); */ $("#grid").jqGrid('setGridParam', {ondblClickRow: function(rowid,iRow,iCol,e){alert('double clicked');}}); });//]]> </script> <script type='text/javascript'> jQuery(document).ready(function () { jQuery("#projectTable").jqGrid({ url: "LoadJsonDataServlet?type=BS21 7RH", datatype: "json", jsonReader: {repeatitems: false, id: "ref"}, colNames:['First Name','Last Name', 'Address'], colModel:[ {name:'firstName',index:'firstName', width:100}, {name:'lastName',index:'lastName', width:100}, {name:'address',index:'address', width:500} ], rowNum:20, rowList:[20,60,100], height:460, pager: "#pagingDiv", viewrecords: true, caption: "Json Example" }); $("#pcSelect").change(function(){ var postcode = $("#pcSelect").val(); jQuery("#projectTable").jqGrid( "setGridParam",{ url:"LoadJsonDataServlet?type="+ postcode, page:1}) .trigger("reloadGrid"); }); }); </script> </head> <body> <table id="grid"></table> <hr> <div> <div class="borderBottom" style="height:5em;"> <div class="floatLeftDiv borderRight"> <div class="padding"> <label>Postcode:</label> <select id="pcSelect"> <option>BS21 7RH</option> <option>BS1 8QT</option> </select> </div> </div> </div> <div> <div style="float: left;"> <table id="projectTable"></table> <div id="pagingDiv"></div> </div> </div> </div> </body> </html>
This comment has been removed by the author.
ReplyDeleteThank you very much for this post... i was able to implement it very easily, in fact any one can.
ReplyDeletethanks
ReplyDeleteSujessh Ashokan & Vasanth: Welcome
ReplyDeleteThanks for so well example but i dont see that you use jsonReader
ReplyDeleteSuper simple
ReplyDeleteNo data is coming in JSON table.
ReplyDeleteCheck for Browser Console using Firebug for error.
ReplyDeleteThe browser console does not show any error.
ReplyDeleteAlso, the very first time the data for Person is not loaded.
I'm using Safari browser.
Thank you very much for this example..
ReplyDeletei think that you don't configure on your project's web.xml (servlet setting)
ReplyDeletecheck your project
@Sang doc Lee: yes that is because of default eclipse dynamic web project setup and by by default it sets to the welcome file to "index.html"
ReplyDeleteGetting Ognl:NoConversationPossible Error
ReplyDeleteI'm facing a issue, please go through the below link where i posted my code in detail.
http://stackoverflow.com/questions/21474295/getting-ognlnoconversationpossible-error
Awesome post
ReplyDeleteEnterprise application development
can you give me your project code? i dont know how to configure web.xml
DeleteThis comment has been removed by the author.
DeleteIn my inner class project , develop a generic component for jqGrid , share and view quice Viewpoint , leave the link to github. https://github.com/OscarMesa/MatrtizEvaluacion/tree/master/src/java/co/edu/poli/util/jqgrid
ReplyDeleteA adequate strategy for learning is to rehash them out to see the dressed liquid and afterward attempt to concur the self validity.java programming
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteAs, for most people, the majority of traffic comes from the search engines this is obviously a very bad thing.
ReplyDeleteSteve