Saturday, 29 June 2013

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>


Categories: , , , ,

24 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Thank you very much for this post... i was able to implement it very easily, in fact any one can.

    ReplyDelete
  3. Sujessh Ashokan & Vasanth: Welcome

    ReplyDelete
  4. Thanks for so well example but i dont see that you use jsonReader

    ReplyDelete
  5. No data is coming in JSON table.

    ReplyDelete
  6. Check for Browser Console using Firebug for error.

    ReplyDelete
  7. The browser console does not show any error.
    Also, the very first time the data for Person is not loaded.

    I'm using Safari browser.

    ReplyDelete
  8. Thank you very much for this example..

    ReplyDelete
  9. i think that you don't configure on your project's web.xml (servlet setting)
    check your project

    ReplyDelete
  10. @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"

    ReplyDelete
  11. Getting Ognl:NoConversationPossible Error

    I'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

    ReplyDelete
  12. Replies
    1. can you give me your project code? i dont know how to configure web.xml

      Delete
    2. This comment has been removed by the author.

      Delete
  13. In 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

    ReplyDelete
  14. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training Core Java 8 Training in Chennai Core java 8 online training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete
  15. Java Online Training Java Online Training Java Online Training Java Online Training Java Online Training Java Online Training

    Hibernate Online Training Hibernate Online Training Spring Online Training Spring Online Training Spring Batch Training Online Spring Batch Training Online

    ReplyDelete
  16. Very good write-up. I definitely appreciate this website. Continue the good work!
    Devops Online Training
    Adobe cq5 Training
    Dell Boomi Training

    ReplyDelete
  17. A adequate strategy for learning is to rehash them out to see the dressed liquid and afterward attempt to concur the self validity.java programming

    ReplyDelete
  18. Daredevil and Bullseye are going to have a face off for sure in Daredevil season 3 as the antagonist is expected to appear in the upcoming installment. Daredevil Season 3 Trailer

    ReplyDelete
  19. This comment has been removed by the author.

    ReplyDelete
  20. As, for most people, the majority of traffic comes from the search engines this is obviously a very bad thing.
    Steve

    ReplyDelete

Find me on Facebook! Follow me on Twitter!