Click here to Skip to main content
15,867,141 members
Articles / Web Development / HTML
Article

Data Grid for JSP

Rate me:
Please Sign up or sign in to vote.
4.70/5 (52 votes)
21 Jul 2006LGPL36 min read 968.9K   20K   96   277
An Asp.Net style grid control for JSP with ability to fetch data from java.sql.Connection or java.util.List or java.sql.ResultSet

Sample Image - DBGrid.png

Introduction

This article presents a Grid control very similar to the one found in ASP.NET, but for JSP pages. Although a data grid can be easily rendered using JSTL for loop tag, it tends to clutter the code and hence debugging can become very difficult. The control presented in this article makes coding such grids a breeze and also it helps one to keep the code clean.

Features at a glance

At present the control implements following things.

  • Data pagination.
  • Sorting by a specified column.
  • Automatic row number display.
  • Image based hyperlink columns.
  • Hyperlink columns.
  • Custom data formatting.
  • Value decoding.
  • Ability to bind to a List.
  • Ability to bind to a ResultSet.
  • Ability to bind to a RowSet.

Apart from this it also allows one to specify column names to be used while constructing the HREF element of the hyperlink. This reference then at runtime automatically gets substituted by the column value. For example the following code snippet

HTML
<grd:imagecolumn headerText="" width="5" HAlign="center" imageSrc="images/Edit.gif" 
    linkUrl="javascript:doEdit('{CLICORPORATION}', '{CLICLIENT}')" imageBorder="0" 
    imageWidth="16" imageHeight="16" alterText="Click to edit"></grd:imagecolumn>
results in following code to be outputted to the browser
HTML
<td WIDTH="5%" ALIGN="center">
    <a HREF="javascript:doEdit('TATA', 'TELCO')">
        <img SRC="images/Edit.gif" BORDER=0 WIDTH=16 HEIGHT=16 ALT="Click to edit">
    </a>
</td>

The Control Details

The DBGrid control consists of following sub controls (classes).

  1. gridpager - This control is responsible for rendering the pager control. This control has following attributes to customize the images displayed for navigation. All these attributes are mandetory attributes.
    • imgFirst - Custom image to be displayed for navigate to first page action.
    • imgPrevious - Custom image to be displayed for navigate to previous page action.
    • imgNext - Custom image to be displayed for navigate to next page action.
    • imgLast - Custom image to be displayed for navigate to last page action.

  2. gridsorter - This control is responsible for providing the sort support. The most important and required attributes for this control are:
    • sortColumn - The name of the column to be used while constructing ORDER BY clause.
    • sortAscending - The boolean value indicating whether to sort in ascending order or descending order.

    Apart from above two attributes this control has following two optional attributes to customize the images that appear in the column header to indicate the current sort order. If not specified the control assumes that ImgAsc.gif and ImgDesc.gif are present in the images folder.

    • imageAscending - Image to be displayed in header of the associated column when the data issorted in ascending order.
    • imageDescending - Image to be displayed in header of the associated column when the data is sorted in descending order.

  3. textColumn - This control is responsible for rendering the text column. The control has following special attributes to control the apperance of the rendered text.
    • maxLength - Controls the number of character to be outputted.

  4. dateColumn - This control is responsible for rendering the date time values. The control has following special attributes to control the apperance of the rendered text.
    • dataFormat - The format string as defined in java.text.DateFormat

  5. numberColumn - This control is responsible for rendering the numeric values. The control has following special attributes to control the apperance of the rendered text.
    • dataFormat - The format string as defined in java.text.DecimalFormat

  6. anchorColumn - This control is responsible for rendering the hyperlinks. This control also supports value substitution as explained in previous section. The control has following special attributes to control the apperance and behavior of the hyperlink.
    • linkText - A fixed string to be used to render the hyperlink. Alternatively one can also specify the column value to be used using dataField attribute
    • linkUrl - The url to be invoked when this link is clicked. This can also be a javascript function.
    • target - The name of the window or frame in which the referenced url is to be opened.

  7. imageColumn - This control is responsible for rendering the hyperlinked image. This control also supports value substitution as explained in previous section. The control has following special attributes to control the apperance and behavior of the hyperlink.
    • imageSrc - The image to be displayed.
    • imageWidth - The width of the image in pixels.
    • imageHeight - The height of the image in pixels.
    • imageBorder - The width of the image border in pixels.
    • alterText - The tooltip text to be displayed.
    • linkUrl - The url to be invoked when this link is clicked. This can also be a javascript function.
    • target - The name of the window or frame in which the referenced url is to be opened.

  8. rownumColumn - This control is responsible for numbering the rows displayed in the gird.

  9. decodeColumn - This control is responsible for decoding the column values and display the decoded text. The control has following special attributes to control the decoding.
    • decodeValues - A string containing values to be decoded seperated by the delimeter specified using valueSeperator attribute.
    • displayValues - A string containing values to be displayed seperated by the delimeter specified using valueSeperator attribute.
    • valueSeperator - The value delimeter.

DBGrid Control Container

The DBGrid control it self has following special properties.

  1. dataSource - Allows one to specify the java.sql.Connection object to be used to fetch the values from database or a java.util.List.
  2. dataMember - The SQL to be used to retrieve the required data. The SQL should not contain the ORDER BY clause. If you are specifying java.util.List for dataSource then this can be left blank.
  3. pageSize - The number of rows to be displayed in a page.
  4. currentPage - The page number to be displayed.

Using the code

following code snippet shows the DBGrid control usage. The same source can also found in the demo application.

jsp
<%@ taglib uri="/WEB-INF/tags/datagrid.tld" prefix="grd" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="com.freeware.gridtag.*" %> 
<%
int intCurr = 1;
int intSortOrd = 0;
String strTmp = null;
String strSQL = null;
String strSortCol = null;
String strSortOrd = "ASC";
boolean blnSortAsc = true; 
strSQL = "SELECT CLICORPORATION, CLICLIENT, CLIDESCRIPTION, " +
         "CLIENABLED, CLIUPDSTAMP FROM CLIENTMASTER "; 
Connection objCnn    = null;
Class      objDrvCls = null;
objDrvCls = Class.forName("oracle.jdbc.driver.OracleDriver");
objCnn = DriverManager.getConnection("jdbc:oracle:thin:@Host:port:sid", 
                                     "cashincpri", "cashincpri");
if (objDrvCls != null) objDrvCls = null;
strTmp = request.getParameter("txtCurr");
try
{
  if (strTmp != null)
  intCurr = Integer.parseInt(strTmp);
}
catch (NumberFormatException NFEx)
{
}
strSortCol = request.getParameter("txtSortCol");
strSortOrd = request.getParameter("txtSortAsc");
if (strSortCol == null) strSortCol = "CLICLIENT";
if (strSortOrd == null) strSortOrd = "ASC";
blnSortAsc = (strSortOrd.equals("ASC"));
%>
<html>
<head>
<title>Grid Tag Demonstration</title>
<link REL="StyleSheet" HREF="css/GridStyle.css">
<script LANGUAGE="javascript">
function doNavigate(pstrWhere, pintTot)
{
  var strTmp;
  var intPg; 
  strTmp = document.frmMain.txtCurr.value;
  intPg = parseInt(strTmp);
  if (isNaN(intPg)) intPg = 1; 
  if ((pstrWhere == 'F' || pstrWhere == 'P') && intPg == 1)
  {
    alert("You are already viewing first page!");
    return;
  }
  else if ((pstrWhere == 'N' || pstrWhere == 'L') && intPg == pintTot)
  {
    alert("You are already viewing last page!");
    return;
  }
  if (pstrWhere == 'F')
    intPg = 1;
  else if (pstrWhere == 'P')
    intPg = intPg - 1;
  else if (pstrWhere == 'N')
    intPg = intPg + 1;
  else if (pstrWhere == 'L')
    intPg = pintTot; 
  if (intPg < 1) intPg = 1;
  if (intPg > pintTot) intPg = pintTot;
  document.frmMain.txtCurr.value = intPg;
  document.frmMain.submit();
}
function doSort(pstrFld, pstrOrd)
{
  document.frmMain.txtSortCol.value = pstrFld;
  document.frmMain.txtSortAsc.value = pstrOrd;
  document.frmMain.submit();
}
</script>
</head>
<body>
<h2>Grid Example</h2>
<form NAME="frmMain" METHOD="post">
<grd:dbgrid id="tblStat" name="tblStat" width="100" pageSize="10" 
    currentPage="<%=intCurr%>" border="0" cellSpacing="1" cellPadding="2" 
    dataMember="<%=strSQL%>" dataSource="<%=objCnn%>" cssClass="gridTable">
 <grd:gridpager imgFirst="images/First.gif" imgPrevious="images/Previous.gif" 
      imgNext="images/Next.gif" imgLast="images/Last.gif"/>
 <grd:gridsorter sortColumn="<%=strSortCol%>" sortAscending="<%=blnSortAsc%>"/>
 <grd:rownumcolumn headerText="#" width="5" HAlign="right"/>
 <grd:imagecolumn headerText="" width="5" HAlign="center" 
      imageSrc="images/Edit.gif" 
      linkUrl="javascript:doEdit('{CLICORPORATION}', '{CLICLIENT}')" 
      imageBorder="0" imageWidth="16" imageHeight="16" 
      alterText="Click to edit"/>
 <grd:textcolumn dataField="CLICLIENT" headerText="Client" 
      width="10" sortable="true"/>
 <grd:textcolumn dataField="CLIDESCRIPTION" headerText="Description" 
      width="50" sortable="true"/>
 <grd:decodecolumn dataField="CLIENABLED" headerText="Enabled" width="10" 
      decodeValues="Y,N" displayValues="Yes,No" valueSeperator=","/>
 <grd:datecolumn dataField="CLIUPDSTAMP" headerText="Last Updated" 
      dataFormat="dd/MM/yyyy HH:mm:ss" width="20"/>
</grd:dbgrid>
<input TYPE="hidden" NAME="txtCurr" VALUE="<%=intCurr%>">
<input TYPE="hidden" NAME="txtSortCol" VALUE="<%=strSortCol%>">
<input TYPE="hidden" NAME="txtSortAsc" VALUE="<%=strSortOrd%>">
</form>
</body>
</html>
<%
try
{
    if (objCnn != null)
        objCnn.close();
}
catch (SQLException SQLExIgnore)
{
}
if (objCnn != null) objCnn = null;
%>

The attached demo zip file also contains the ddl and dml which you can directly use to create the necessary table and populate the test data. I have tested this control using oracle database and the jdbc thin driver. For other databases you may have to change the dml.

References

The links which helped me a lot in designing this control library,

History

  • July 27, 2004 - Initial release.
  • May 12, 2005 - Added support for List. DBGrid can now render data supplied as object list. Changed names of sourceSQL to dataMember and connection to dataSource. Updated sample application to demonstrate the same.
  • June 03, 2005 - Updated the sample code in article to reflect the changes made in last release.
  • January 10, 2006 - Added support for ResultSet and RowSet. Added new sample RawJDBCGrid.jsp page to demonstrate this. While supplying these types of object as dataSource care must be taken to make this ResultSet SCROLLABLE (ie. ResultSet.TYPE_SCROLL_INSENSITIVE).
  • April 07 2006 - Fixed the bug in page navigation. Credit goes to Member No. 2833981 for pointing out this bug.
  • July 22, 2006 - Small bug fix to allow multiple dbgrids on single page. All credit goes to to Dave Lilley for pointing out this bug as well as suggesting the solution.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


Written By
Software Developer (Senior) Freelancer
India India
I am a software professional with over 20 years of commercial business applications design and development experience.

My programming experience includes Java, Spring, .NET, Classic VB & ASP, Scripting, Power Builder, PHP, Magic & far far ago FoxPro, C, Assembly and COBOL.

From last 11 years I am mostly working with Java Technology. I am currently available to take up new assignments.

Comments and Discussions

 
QuestionHow can get Pagination with Numbers(1 2 3 4 5 6 7 8 9 10 Next) Pin
ashokadcrl12-Jun-08 1:36
ashokadcrl12-Jun-08 1:36 
Generali am not able to use this grid in my application Pin
renjithpaul18-Apr-08 0:08
renjithpaul18-Apr-08 0:08 
GeneralRe: i am not able to use this grid in my application Pin
niket_shah8330-Apr-09 0:23
niket_shah8330-Apr-09 0:23 
QuestionNumer field not showing Pin
Bisweswar26-Dec-07 19:40
Bisweswar26-Dec-07 19:40 
AnswerRe: Numer field not showing Pin
JMVillaG3-Apr-08 9:50
JMVillaG3-Apr-08 9:50 
QuestionCan I insert and update values into the grid Pin
Member 31100629-Dec-07 21:08
Member 31100629-Dec-07 21:08 
Questionhow to use list Pin
sumouser13-Nov-07 23:00
professionalsumouser13-Nov-07 23:00 
Generalgenerating rows using JSP Pin
lamarjones7-Sep-07 4:06
lamarjones7-Sep-07 4:06 
GeneralRe: generating rows using JSP Pin
iren1-Apr-08 6:19
iren1-Apr-08 6:19 
QuestionIs Multiple Grid Code available? Pin
nyy_28-Aug-07 5:27
nyy_28-Aug-07 5:27 
GeneralPrinting grid data.. Pin
VaibhavTiparadi6-Aug-07 0:32
VaibhavTiparadi6-Aug-07 0:32 
GeneralRe: Printing grid data.. Pin
vishaldsh8-Dec-09 21:25
vishaldsh8-Dec-09 21:25 
GeneralRe: Printing grid data.. Pin
VaibhavTiparadi9-Dec-09 1:05
VaibhavTiparadi9-Dec-09 1:05 
Questionsecurity alert popup. Pin
techmalli25-Jul-07 7:39
techmalli25-Jul-07 7:39 
GeneralGive and take, I talk about my edit, you tell me your thoughts on printing.... Pin
lamarjones25-Jul-07 3:48
lamarjones25-Jul-07 3:48 
Generala request from johnson joseph Pin
Sean Ewington23-Jul-07 4:18
staffSean Ewington23-Jul-07 4:18 
GeneralLicense - supported J2EE level Pin
jfqjfq9-Jul-07 23:36
jfqjfq9-Jul-07 23:36 
GeneralEditable Grid Pin
fuzzysoft14-Jul-07 22:31
fuzzysoft14-Jul-07 22:31 
QuestionExample of doEdit()? Pin
Kevin Ternes3-Jul-07 5:24
Kevin Ternes3-Jul-07 5:24 
QuestionHow to implement edit function Pin
AP_java2-Jun-07 2:44
AP_java2-Jun-07 2:44 
QuestionError in using tag library uri='/WEB-INF/datagrid.tld' Pin
Nirmal tony1-Jun-07 2:30
Nirmal tony1-Jun-07 2:30 
QuestionDatagrid using Resultset Pin
yogesh_prajapati30-May-07 3:11
yogesh_prajapati30-May-07 3:11 
GeneralNewb taglib conceptual error: Missing tagclass for tag "dbgrid" Pin
geoffalot28-May-07 9:03
geoffalot28-May-07 9:03 
GeneralRe: Newb taglib conceptual error: Missing tagclass for tag "dbgrid" Pin
Prasad Khandekar31-May-07 5:07
professionalPrasad Khandekar31-May-07 5:07 
Questionnumbercolumn: number not show Pin
phoebeching24-May-07 14:45
phoebeching24-May-07 14:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.