Create Data Grid in JSP page

This is detailed code that how to create data grid that shows data from database table in jsp page.

Create Data Grid in JSP page


This is detailed code that how to create data grid that shows data from database table in jsp page. In this jsp code given below we have used a tag library that provide some tags to create data grid. This code also provide facility to create paging and sorting, we can also specify number of data we want to see in one single page. This tag library provides some functions to calculate average and total.

First create table form where this data grid will fetch data and show in a jsp page. We have used database name 'mahendra' in this code and fetch data from table named 'employee_master' in same database.

Structure of table employee_master

CREATE TABLE `employee_master` (             
                   `emp_id` int(10) NOT NULL auto_increment,  
                   `firstName` varchar(20) default NULL,      
                   `lastname` varchar(20) default NULL,       
                   `salary` double default NULL,              
                   `bonus` double default NULL,               
                   PRIMARY KEY  (`emp_id`)                    


     <title>Example, Data Grid in jsp page</title>
    <%@ page contentType="text/html"%>
    <%@ page import="java.util.*, org.apache.taglibs.datagrid.
        DataGridParameters, java.sql.*" %>
    <%@ taglib uri="" 
        prefix="ui" %>
    <%@ taglib uri="" prefix="c" %>
    <%@ taglib uri="" prefix="fmt" %>
	<%! public class Employee {
	    protected String firstName;
	    protected String lastName;
	    protected double salary;
	    protected double bonus;
	    public String getFirstName () {
		return (firstName);
		     public String getLastName (){
			return (lastName);
		     public double getSalary () {
			return (salary);
		     public double getBonus () {
			return (bonus);
		      public void setFirstName (String newFirstName)
				firstName = newFirstName;
			  public void setLastName (String newLastName)
				lastName = newLastName;
			  public void setSalary (double newSalary)
				salary = newSalary;
			  public void setBonus (double newBonus)
				bonus = newBonus;
	<%  ArrayList employees = new ArrayList ();
	   Employee  objEmployee;
	     int fromIndex, toIndex;
	      try {
		String connectionURL = "jdbc:mysql://localhost:3306/mahendra";
	            Connection connection = null;
				Statement statement = null;
                ResultSet rs = null;
                connection = DriverManager.getConnection(connectionURL, 
                "root", "root");
                statement = connection.createStatement();
                String QueryString = "SELECT * from employee_master";
                rs = statement.executeQuery(QueryString);
			while ( {		
			objEmployee = new Employee ();
    catch (Exception ex) {
            System.out.println("Unable to connect to batabase."+ex);
   fromIndex = (int) DataGridParameters.getDataGridPageIndex (request, 
   if ((toIndex = fromIndex+4) >= employees.size ())
  toIndex = employees.size();
   request.setAttribute ("employees", employees.subList(fromIndex, toIndex));
    th a:link      { text-decoration: none; color: black }
     th a:visited   { text-decoration: none; color: black }
     .rows          { background-color: white }
     .hiliterows    { background-color: #848484; color: white; 
                      font-weight: bold }
     .alternaterows { background-color: #D8D8D8 }
     .header        { background-color: #2E2E2E; color: #D8D8D8;font-weight: 
                      bold }
	     .datagrid      { border: 1px solid #C7C5B2; font-family: arial; 
                      font-size: 9pt;
	    font-weight: normal }
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
   <ui:dataGrid items="${employees}" var="employee" name="datagrid1" 
    cellSpacing="0" styleClass="datagrid">
   <column width="50">
      <header value="Select" hAlign="center" styleClass="header"/>
        <input type="checkbox" align="center" name="employee" 
		    value="${employee.firstName} ${employee.lastName}"/>
      <aggregate function="count" var="total"/>
    <column width="150">
      <header value="Name" hAlign="center" styleClass="header"/>
      <item   value="${employee.firstName} ${employee.lastName}" hAlign="left" 
	     hyperLink="" hyperLinkTarget="_blank" 
      <aggregate function="count" var="total"/>
    <column width="200">
      <header value="Salary (INR)" hAlign="center" styleClass="header"/>
      <item   value="${employee.salary}" hAlign="right" pattern="#,##0.00 
         " styleClass="item"/>
      <aggregate function="avg" pattern="#,##0.00 " var="total"/>      
    <column width="200">
      <header value="Bonus (INR)" hAlign="center" styleClass="header"/>
      <item   value="${employee.bonus}" hAlign="right" pattern="#,##0.00 " 
      <aggregate function="avg" pattern="#,##0.00 " var="total"/>  
  <rows          styleClass="rows" hiliteStyleClass="hiliterows"/>
  <alternateRows styleClass="alternaterows"/>
  <paging        size="4" count="11" custom="true" nextUrlVar="next" 
       previousUrlVar="previous" pagesVar="pages"/>
  <order         imgAsc="up.gif" imgDesc="down.gif"/>
<table width="500" style="font-family: arial; font-size: 10pt">
<td align="left" width="33%">
<c:if test="${previous != null}">
<a href="<c:out value="${previous}"/>">Previous</a>
<td align="center" width="33%">
<c:forEach items="${pages}" var="page">
  <c:when test="${page.current}">
    <b><a href="<c:out value="${page.url}"/>">
                 <c:out value="${page.index}"/></a></b>
    <a href="<c:out value="${page.url}"/>"><c:out value="${page.index}"/></a>
<td align="right" width="33%">&nbsp;
<c:if test="${next != null}">
<a href="<c:out value="${next}"/>">Next</a>

When user clicks on link 'next' this shows next four data from the table......

Download Source Code

Share on Google+Share on Google+

Create Data Grid in JSP page

Posted on: July 29, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Create Data Grid in JSP page   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
April 20, 2011
How to get selected value of combobox

In the above example how can we get value of selected check boxes. Suppose if we use radio button instead of check box then also how to retrive the value.
Prince Grover
September 15, 2011

Dear Sir/Ma'm I want to use this grid in my project and i am using eclipse so please tell me how can i run this code in eclipse as tld file is not working in eclipse Thanks Prince Grover
December 3, 2011
grids in jsp

Hi, how could I get the datagrid API? where is it?
deepak singh
May 14, 2012
how to jsp data in grid form

the above example fetch firstname and lastname from database but it shows null value for salary and bonus. plz check the above code and give me the correct code.
August 25, 2012
Regarding pagination code

It shows following error: org.apache.jasper.JasperException: /paging.jsp(93,0) According to TLD or attribute directive in tag file, attribute items does not accept any expressions at org.apache.jasper.compiler.DefaultErrorHandler.jspError( at org.apache.jasper.compiler.ErrorDispatcher.dispatch( at org.apache.jasper.compiler.ErrorDispatcher.jspError( at org.apache.jasper.compiler.Validator$ValidateVisitor.checkXmlAttributes( at org.apache.jasper.compiler.Validator$ValidateVisitor.visit( at org.apache.jasper.compiler.Node$CustomTag.accept( at org.apache.jasper.compiler.Node$Nodes.visit( at org.apache.jasper.compiler.Node$Visitor.visitBody( at org.apache.jasper.compiler.Node$Visitor.visit( at org.apache.jasper.compiler.Node$Root.accept( at org.apache.jasper.compiler.Node$Nodes.visit( at org.apache.jasper.compiler.Validator.validateExDirectives( at org.apache.jasper.compiler.Compiler.generateJava( at org.apache.jasper.compiler.Compiler.compile( at org.apache.jasper.compiler.Compiler.compile( at org.apache.jasper.compiler.Compiler.compile( at org.apache.jasper.JspCompilationContext.compile( at org.apache.jasper.servlet.JspServletWrapper.service( at org.apache.jasper.servlet.JspServlet.serviceJspFile( at org.apache.jasper.servlet.JspServlet.service( at javax.servlet.http.HttpServlet.service( at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter( at org.apache.catalina.core.ApplicationFilterChain.doFilter( at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter( at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter( at org.apache.catalina.core.ApplicationFilterChain.doFilter( at org.apache.catalina.core.StandardWrapperValve.invoke( at org.apache.catalina.core.StandardContextValve.invoke( at at at at at org.apache.catalina.core.StandardHostValve.invoke( at org.apache.catalina.valves.ErrorReportValve.invoke( at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke( at org.apache.catalina.core.StandardEngineValve.invoke( at org.apache.catalina.connector.CoyoteAdapter.service( at org.apache.coyote.http11.Http11Processor.process( at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process( at$ at Source)
September 11, 2012

i didn't understand this code!!! pls give me the brief explanation about this code thanking u
October 3, 2013
Error in Datagrid query.

I Have implemented Datagrid, and i stuck in : <ui:dataGrid items="${ServerMaster}" var="servermaster" name="datagrid1" cellPadding="0" cellSpacing="0" styleClass="datagrid" width="985px" > and Showing error as :- According to TLD or attribute directive in tag file, attribute items does not accept any expressions
September 7, 2012
create data grid in jsp

org.apache.jasper.JasperException: /admin.jsp(171,0) PWC6236: According to TLD or attribute directive in tag file, attribute test does not accept any expressions on using above code i got this error....what should i do to resolve it.....plz....its urgent...