Home Jsp Create Data Grid in JSP page

Related Tutorials


 
 

Share on Google+Share on Google+

Create Data Grid in JSP page

Advertisement
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`)                    
                 )

data_grid.jsp

<html>
  <head>
     <title>Example, Data Grid in jsp page</title>
  </head>
  <body>
    <%@ page contentType="text/html"%>
    <%@ page import="java.util.*, org.apache.taglibs.datagrid.
        DataGridParameters, java.sql.*" %>
    <%@ taglib uri="http://jakarta.apache.org/taglibs/datagrid-1.0" 
        prefix="ui" %>
    <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
    <%@ taglib uri="http://java.sun.com/jstl/fmt" 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;
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                connection = DriverManager.getConnection(connectionURL, 
                "root", "root");
                statement = connection.createStatement();
                String QueryString = "SELECT * from employee_master";
                rs = statement.executeQuery(QueryString);
			while (rs.next()) {		
			objEmployee = new Employee ();
			objEmployee.setFirstName(rs.getString("firstname"));
			objEmployee.setLastName(rs.getString("lastname"));
			objEmployee.setSalary(rs.getDouble("salary"));
			objEmployee.setBonus(rs.getDouble("bonus"));
			employees.add(objEmployee);
		}
  			rs.close();
			statement.close();
					connection.close();
				} 
    catch (Exception ex) {
            System.out.println("Unable to connect to batabase."+ex);
        }
   fromIndex = (int) DataGridParameters.getDataGridPageIndex (request, 
               "datagrid1");
   if ((toIndex = fromIndex+4) >= employees.size ())
  toIndex = employees.size();
   request.setAttribute ("employees", employees.subList(fromIndex, toIndex));
%>
   <style>
    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 }
   </style>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
   <ui:dataGrid items="${employees}" var="employee" name="datagrid1" 
 cellPadding="0" 
    cellSpacing="0" styleClass="datagrid">
  <columns>
   <column width="50">
      <header value="Select" hAlign="center" styleClass="header"/>
     <item>
	  <![CDATA[
        <input type="checkbox" align="center" name="employee" 
		    value="${employee.firstName} ${employee.lastName}"/>
        ]]>
      <aggregate function="count" var="total"/>
     	  </item>
    </column>
    <column width="150">
      <header value="Name" hAlign="center" styleClass="header"/>
      <item   value="${employee.firstName} ${employee.lastName}" hAlign="left" 
	     hyperLink="http://www.roseindia.net" hyperLinkTarget="_blank" 
             styleClass="item"/>
      <aggregate function="count" var="total"/>
       </column>
    <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>
    <column width="200">
      <header value="Bonus (INR)" hAlign="center" styleClass="header"/>
      <item   value="${employee.bonus}" hAlign="right" pattern="#,##0.00 " 
       styleClass="item"/>
      <aggregate function="avg" pattern="#,##0.00 " var="total"/>  
           </column>
  </columns>
  <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"/>
</ui:dataGrid>
<table width="500" style="font-family: arial; font-size: 10pt">
<tr>
<td align="left" width="33%">
<c:if test="${previous != null}">
<a href="<c:out value="${previous}"/>">Previous</a>
</c:if>&nbsp;
</td>
<td align="center" width="33%">
<c:forEach items="${pages}" var="page">
<c:choose>
  <c:when test="${page.current}">
    <b><a href="<c:out value="${page.url}"/>">
                 <c:out value="${page.index}"/></a></b>
  </c:when>
  <c:otherwise>
    <a href="<c:out value="${page.url}"/>"><c:out value="${page.index}"/></a>
  </c:otherwise>
</c:choose>
</c:forEach>
</td>
<td align="right" width="33%">&nbsp;
<c:if test="${next != null}">
<a href="<c:out value="${next}"/>">Next</a>
</c:if>
</td>
</tr>
</table>
</body>
</html>

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

Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 29, 2008

Related Tutorials

Discuss: Create Data Grid in JSP page   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:8
Mudit
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
Data-Grid

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
Yomero
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.
Sachin
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(DefaultErrorHandler.java:40) at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407) at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:148) at org.apache.jasper.compiler.Validator$ValidateVisitor.checkXmlAttributes(Validator.java:1173) at org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:820) at org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1530) at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2359) at org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2409) at org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2415) at org.apache.jasper.compiler.Node$Root.accept(Node.java:495) at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2359) at org.apache.jasper.compiler.Validator.validateExDirectives(Validator.java:1735) at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:184) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:333) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:313) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:300) at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:585) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:312) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:322) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:249) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190) at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92) at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126) at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source)
devi
September 11, 2012
jsp

i didn't understand this code!!! pls give me the brief explanation about this code thanking u
Kapil
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
neha
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...
DMCA.com