Using DataGrid in JSP-Servlet

Using DataGrid in JSP-Servlet (Json)

In Jsp-Servlet , DataGrid can be implemented in many ways, you can write own method ,Here we are using Jquery EasyUI Datagrid in jsp-servlet project.

Step1:
Add required JAR files into lib

  1. commons-beanutils-1.8.1.jar
  2. commons-collections-3.2.1.jar
  3. commons-lang-2.5.jar
  4. commons-logging-1.1.1.jar
  5. ezmorph-1.0.6.jar
  6. json-lib-2.4-jdk15.jar
  7. json-rpc-1.0.jar
  8. mysql-connector-java-5.1.18-bin.jar

Step2:
Create bean class(World.java) which will hold each row data.

package com.stringpool.bean;

public class World {
    private String code;
    private String name;
    private String continent;
    private String region;

    /**
     * @return the code
     */
    public String getCode() {
        return code;
    }

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

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

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

    /**
     * @return the continent
     */
    public String getContinent() {
        return continent;
    }

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

    /**
     * @return the region
     */
    public String getRegion() {
        return region;
    }

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

Step2 :
Create a JSP page(index.jsp) and add following lines in <head> tag of jsp page.you can download all these files and can attach from your server path.

<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/demo/demo.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="http://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>

Step3 : Add these code where you want your DataGrid

<table id="tt" class="easyui-datagrid" style="width:500px;height:250px"
url="servlet/ResponseServlet"
title="Searching" iconCls="icon-search" toolbar="#tb"
rownumbers="true" pagination="true" >
<thead>
<tr>
<th field="code" width="100">Code</th>
<th field="continent" width="100">Continent</th>
<th field="name" width="100" align="right">Name</th>
<th field="region" width="140" align="right">Region</th>
</tr>
</thead>
</table>

Note: Here field name should be same as bean properties name.

Step4 :If you want to add search fields in your datagrid, add following code after your table,its display two text box in datagrid.

<div id="tb" style="padding:3px">
<span>Continent:</span>
<input id="cname" style="line-height:26px;border:1px solid #ccc">
<span>Region:</span>
<input id="region" style="line-height:26px;border:1px solid #ccc">
<a href="#" class="easyui-linkbutton" plain="true" onclick="doSearch()">Search</a>
</div

and add these lines in <Head> tag

<script type="text/javascript">
function doSearch(){
$('#tt').datagrid('load',{
cname: $('#cname').val(),
region: $('#region').val()
});
}</script>

The above code is a jquery function which execute when user click on search , it will send text value to servlet.but remember one thing ,you only get these value on servlet using

String cname=request.getParameter("cname")==null?"":request.getParameter("cname");
String region=request.getParameter("region")==null?"":request.getParameter("region");

Step5 :Create a servlet(ResponseServlet.java) which will return JSON type data to JSP page.

package com.stringpool.com;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.stringpool.bean.World;
import com.stringpool.db.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

public class ResponseServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		System.out.println("Get...");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		//Get page and rows value from JSP page
		int page=Integer.parseInt(request.getParameter("page"));
		int rows=Integer.parseInt(request.getParameter("rows"));

		//Get Search box values 
		String cname=request.getParameter("cname")==null?"":request.getParameter("cname");
		String region=request.getParameter("region")==null?"":request.getParameter("region");

		//Calculate offset value
		int offset = (page-1)*rows;

		//Define Database Connection & ResultSet
		DBUtil db=new DBUtil();
		Connection con=db.getConnect();
		ResultSet rs=null;
		PreparedStatement ps=null,ps1=null;

		//JSON object
		JSONObject json = new JSONObject();

		//Create List to store all objects
		List<World> worlds = new ArrayList<World>();

		//total Records 
		int total=0;

		//where clause query for search
		String where = "continent like '%"+cname+"%' and region like '%"+region+"%'";

		//your SQL query
		String sql="select * from country where "+where+" limit "+offset+","+rows;

		//SQL query to count total no of records
		String count = "select count(*) from country where "+where;

		//Execute all queries here
		try {
			ps=con.prepareStatement(count);
			ResultSet rs2=ps.executeQuery();
			if(rs2.next())
			{ total=rs2.getInt(1);}

			//put total no records in json object with total key 
			json.put("total",total);

			ps1=con.prepareStatement(sql);
			rs=ps1.executeQuery();

			while(rs.next())
			{

				//create every time a new object to store rows data
				World wd=new World();
				wd.setCode(rs.getString("code"));
				wd.setContinent(rs.getString("continent"));
				wd.setName(rs.getString("name"));
				wd.setRegion(rs.getString("region"));
				worlds.add(wd);
			}

			//put arraylist in json with rows key
			json.put("rows", worlds);

		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		finally {
			try {if(rs!=null)rs.close();}catch(SQLException e) {e.printStackTrace();}
			try {if(ps!=null)ps.close();}catch(SQLException e) {e.printStackTrace();}
			try {if(ps1!=null)ps1.close();}catch(SQLException e) {e.printStackTrace();}
			try {if(con!=null)con.close();}catch(SQLException e) {e.printStackTrace();}}

		//return json data to JSP page
		out.print(json);

		out.flush();
		out.close();
	}

}

 

Output:

DataGrid example:

pagination

DataGrid Search :

pagination-search

Download:

Download

References:

 jQuery EasyUI

Tags: , ,

22 comments

  1. Joshua says:

    i m not able to display data on the datagrid .Also when i m using out.println(“Ïnside the Post”); within the ResponseServlet it also not displaying on the page .Can u help me out

    • admin says:

      I think there will be problem in your servlet,So first check your servlet if it’s ok then check JSON format.You can check JSON error details in firefox or chrome console.

      • Joshua says:

        first thing how to check json error detaials on console .I m new to it.

        when i use system.out.println to display json data it shows me in the console .But the data is not reflecting in the datagrid. attach the code

        public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        //doGet(request, response);
        response.setContentType(“text/html”);
        PrintWriter out = response.getWriter();
        out.print(“HAi servlet”);
        System.out.println(“Hello”);
        //Get page and rows value from JSP page
        int page=Integer.parseInt(request.getParameter(“page”));
        int rows=Integer.parseInt(request.getParameter(“rows”));

        //Get Search box values
        String cname=request.getParameter(“cname”)==null?”":request.getParameter(“cname”);
        String region=request.getParameter(“region”)==null?”":request.getParameter(“region”);

        //Calculate offset value
        int offset = (page-1)*rows;
        //Define Database Connection & ResultSet
        DBUtil db=new DBUtil();
        Connection con=db.getConnect();
        ResultSet rs=null;
        PreparedStatement ps=null,ps1=null;
        //JSON object
        JSONObject json = new JSONObject();

        //Create List to store all objects
        List worlds = new ArrayList();

        //total Records
        int total=0;

        //where clause query for search

        String where = “continent like ‘%”+cname+”%’ and region like ‘%”+region+”%’”;

        String sql=”select * from country where “+where+” limit “+offset+”,”+rows;

        String count = “select count(*) from country where “+where;

        try {

        ps=con.prepareStatement(count);
        ResultSet rs2=ps.executeQuery();
        if(rs2.next())
        { total=rs2.getInt(1);}

        //put total no records in json object with total key
        json.put(“total”,total);

        ps1=con.prepareStatement(sql);
        rs=ps1.executeQuery();

        while(rs.next())
        {

        //create every time a new object to store rows data
        World wd=new World();
        wd.setCode(rs.getString(“code”));
        wd.setContinent(rs.getString(“continent”));
        wd.setName(rs.getString(“name”));
        wd.setRegion(rs.getString(“region”));
        worlds.add(wd);
        }
        json.put(“total”,total);
        //put arraylist in json with rows key
        json.put(“rows”, worlds);
        String gStatus = new String();
        gStatus=json.toString();
        response.setContentType(“application/json”);
        response.setCharacterEncoding(“UTF-8″);
        System.out.println(gStatus);
        } catch (SQLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        }
        finally {
        try {if(rs!=null)rs.close();}catch(SQLException e) {e.printStackTrace();}
        try {if(ps!=null)ps.close();}catch(SQLException e) {e.printStackTrace();}
        try {if(ps1!=null)ps1.close();}catch(SQLException e) {e.printStackTrace();}
        try {if(con!=null)con.close();}catch(SQLException e) {e.printStackTrace();}}
        //return json data to JSP page
        // out.print(json.toString());
        out.println(json);

        out.flush();
        out.close();
        }

        }

  2. Joshua says:

    i m able to view data in the grid. thanks for the help.Now i m not able the values from easyui datagrid to database .When i m getting the values in servlets it is returning null values .

    if u can provide me links for help.

  3. Mayank says:

    Hi,

    I am not able to view data in grid
    and when i debug my call doesn’t go to Servlet.

    can you tell me where i am mistaking ?
    I am badly struck
    pls help

  4. Bharath says:

    Hi Admin,

    Need your help on below.

    As per your demo, we are able to view the grid exactly as shown in above screenshot. But while loading of the page we getting error “length is null or not an object” which occurs in jquery.easyui.min.js file.

    Reference Line No: 8833

    var _660=[""];

    for(var i=0;i<rows.length;i++){

    can you pls guide us how this rows gets populated. Kindly do the needful.

  5. Bharath says:

    We are downloading css file from http://www.jeasyui.com/easyui/demo/demo.css, but its internally contains few images file.

    Can you kindly share the path of images files to download.

  6. John says:

    How can u make jquery easyui combox dynamic with editable datagrid .

  7. Janki says:

    In above code how we can insert a data using database connection.

  8. Ramya says:

    i could not find page, rows in jsp. Where are these in jsp page. How does total and rows in json.put link to the datagrid.

    int page=Integer.parseInt(request.getParameter(“page”));
    int rows=Integer.parseInt(request.getParameter(“rows”));
    json.put(“total”,total);
    json.put(“rows”, worlds);

  9. Ernesto says:

    Hi,

    I am not able to view data in grid. This returns the servlet: {“total”:1,”rows”:["Controlador.World@f6316f"]}

    I think the js can not read the object World.

    Any suggestions?

    Thanks

  10. Jinal says:

    here example shows the data in grid from json format…i want to it with xml…can u please give me example of that???

  11. bharath says:

    How to show “No Results Found” in data grid result set if not data found in Database.

    Kindly assist.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


9 + = twelve

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">