JQGrid Example

Integerating JQGrid in JSP

jqgrid.jsp

<!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=UTF-8">
        <title>JQGrid Special</title>                
        <script src="gridJS/jquery-1.4.3.min.js"  type="text/javascript"></script>
        <script src="gridJS/grid.locale-en.js"  type="text/javascript"></script>
        <script src="gridJS/jquery.jqGrid.min.js" type="text/javascript"></script>
        <link href="gridJS/jquery-ui-1.8.6.custom.css" rel="stylesheet" type="text/css" />
        <link href="gridJS/ui.jqgrid.css" rel="stylesheet" type="text/css" />
        <link href="gridJS/ui.multiselect.css" rel="stylesheet" type="text/css" />
        <script>
            function fillGridOnEvent(){
                $("#jQGrid").html("<table id=\"list\"></table><div id=\"page\"></div>");
                jQuery("#list").jqGrid({
                    url:'<%=request.getContextPath()%>/JQGridServlet?q=1&action=fetchData',
                    datatype: "xml",
                    height: 250,
                    colNames:['Sr. No.','Student Name','Student Std.','Student RollNo.',"Action"],
                    colModel:[
                        {name:'srNo',index:'srNo', width:90,sortable:true},
                        {name:'stdName',index:'stdName', width:130,sortable:false},
                        {name:'stdStd',index:'stdStd', width:100,sortable:false},
                        {name:'stdRollNo',index:'stdRollNo', width:180,sortable:false},
                        {name:'view',index:'view', width:100,sortable:false}
                    ],
                    multiselect: false,
                    paging: true,
                    rowNum:10,
                    rowList:[10,20,30],
                    pager: $("#page"),
                    loadonce:true,
                    caption: "Student Details"
                }).navGrid('#page',{edit:false,add:false,del:false});
            }
            jQuery().ready(function (){
                //fillGrid();
            });
        </script>
    </head>
    <body onload="fillGridOnEvent();">
        <div id="jQGrid" align="center">
        </div>
    </body>
</html>

Servlet(JQGridServlet) returns xml data for grid

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.mycompany.taher;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class JQGridServlet extends HttpServlet {
   
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {        
        PrintWriter out = response.getWriter();
         try {

            if (request.getParameter("action").equals("fetchData")) {
                response.setContentType("text/xml;charset=UTF-8");                

                String status = request.getParameter("status");

                String rows = request.getParameter("rows");
                String page = request.getParameter("page");
                

                int totalPages = 0;
                int totalCount = 15;
                
                if (totalCount > 0) {
                    if (totalCount % Integer.parseInt(rows) == 0) {
                        totalPages = totalCount / Integer.parseInt(rows);
                    } else {
                        totalPages = (totalCount / Integer.parseInt(rows)) + 1;
                    }

                } else {
                    totalPages = 0;
                }
                out.print("<?xml version='1.0' encoding='utf-8'?>\n");
                out.print("<rows>");
                out.print("<page>" + request.getParameter("page") + "</page>");

                out.print("<total>" + totalPages + "</total>");
                out.print("<records>" + 15 + "</records>");
                int srNo = 1;
                
                for (int i=0;i<15;i++) {
                    out.print("<row id='" + i + "'>");
                    out.print("<cell>" + srNo + "</cell>");
                    out.print("<cell>Taher</cell>");
                    out.print("<cell>8th</cell>");
                    out.print("<cell>25</cell>");
                    out.print("<cell><![CDATA[<a href='ViewStd.jsp'>View</a>]]></cell>");
                    out.print("</row>");
                    srNo++;                
                }
                out.print("</rows>");
            }

        } finally {
            out.close();
        }
    } 

    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

   
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    
    @Override
    public String getServletInfo() {
        return "Short description";
    }

}

Below is the output
Jq Grid

About these ads
This entry was posted in JQuery, JSP. Bookmark the permalink.

50 Responses to JQGrid Example

  1. Mwogi J. S. says:

    Simple and precise jqgrid example. Just what i needed.

    Cheers!! ;-)

  2. ilgar Jafarov says:

    great !!!! thank you very much .

  3. rohith says:

    This post is really gud and can you please share an example involving add/edit/delete from jqgrid using ajax request?

  4. raduen says:

    Thanks Thanks Thanks, was looking for this a long time.

  5. chandrashekhar says:

    i am looking for some sorting like stuff

  6. zerta says:

    Thank you

  7. empire says:

    Thank you for nice example. I used the same code. most of the functionalities are working fine…but when I try to change the option for number of rows to display in the grid then its not changing the grid rows…any suggestions ?

  8. empire says:

    when I said “changing the grid rows” means resizing the grid

  9. Pretty great post. I just stumbled upon your weblog and wanted to mention that I have really loved surfing around your weblog posts. After all I will be subscribing for your rss feed and I hope you write again very soon!

  10. I do not even know how I finished up here, but I assumed this post was good. I do not recognize who you are however definitely you are going to a well-known blogger should you are not already ;) Cheers!

  11. Pretty component of content. I simply stumbled upon your web site and in accession capital to say that I acquire actually loved account your weblog posts. Anyway I?ll be subscribing on your feeds or even I success you get right of entry to persistently fast.

  12. sansuds says:

    HI It is a great post, thanks for it.
    I got a situation that I am using column chooser for filtering column display and I want to store the selected column list to the user so that when the user logs in next time he gets the screen with the last chosen columns to display. Where can I capture the list of columns selected to display in the grip?
    Thanks
    Sudha

  13. Ale}{ey says:

    Thanks a lot:)

  14. xavier says:

    Thanks a lot for the post. Can u Pls tell me how to display next and previous button in the navigation bar.

  15. Deep says:

    Please extend this example by enabling edit, add and delete in JQGrid.

  16. chan says:

    Hi,
    Do you the sample code to handle add/delete in JSGRID with JSP?

  17. sazeed says:

    hi i want to integrate java with jgrid……pls help me

  18. luigi says:

    me ha resultado muy útil!
    muchas gracias

  19. layhon says:

    no me carga los datos, puedes especificar mejor sobre el url: ‘? / JQGridServlet q = 1 & action = fetchData’,……..creo k ahi esta el problema y si puedes mostrar la raiz de las carpetas el proyecto para ver la ubicacion correcta

  20. layhon says:

    lo solucione…paso k no cargo el serlet en el web.xml…………quisiera saber sobre la parte de edicion add.edit.deleted….como puedo saber cuando presione que boton para asi poder hacer la edicion……..

  21. vikas says:

    Nice tutorial …Thnx and Keep it up !! .
    Sir ,plz give me codes for loading data from database into Grid with add,edit,delete functionality.
    Thanx In advance ..Sir..

  22. vikas says:

    Sir plz send me the code for database data loading ….
    and guide me for extending add,edit.delete functionality…

    Thanx in advance….

    • yk says:

      can you update on “ViewStd.jsp”
      I want When we click on view that record will show in read mode in new window
      can we maintain same look and feel for view page
      Thanks in advance….

  23. abhishek says:

    plz share the web.xml also ….i did the same thing but not getting results , so will u plz share it ..thank’s for tht

  24. abhishek says:

    i m done ..thank’s

  25. Anonymous says:

    awesome dude thanks a lot!!!!!!!!!!!!!!!

  26. kidkaka1412 says:

    cant you post source ?

  27. Bala says:

    Great Post, thanks

  28. Hira says:

    could plz help to get the source code for this example..thanks in advance

  29. Yusfita says:

    thanks. it works :D

  30. pushpak says:

    i am getting xml response but i am unable to show it on jsp,please help

  31. vas says:

    Hello Sir, can you give me as a .war file, my source is not working,

  32. Your way of explaining the whole thing in this post is genuinely good,
    every one be able to without difficulty understand it, Thanks
    a lot.

  33. Dima says:

    I ran this example, and at first I mapped the servlet incorrectly. As a result I saw an empty grid, but it was a complete grid. Just, unfilled Thanks.
    However, when I fixed servlet mapping, I am getting exception – null pointer exception, and it originates in the
    String rows = request.getParameter(“rows”);
    String page = request.getParameter(“page”);
    Both of these (rows and page) are nulls. I could not understand where those parameters are comming from?
    ?q=1&action=fetchData on the URL I understand fine, but where are the other 2?
    Thanks

  34. pawan says:

    Simple example which java programmer need
    many many
    thanks

  35. bhuvi says:

    Getting Ognl:NoConversationPossible Error

    I’m getting some issue, i posted my code in detail. please check with the below link..

    http://stackoverflow.com/questions/21474295/getting-ognlnoconversationpossible-error

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s