Creating Highly Functional Tables in JSP Using DisplayTag and JavaScript

Creating Highly Functional Tables in JSP Using DisplayTag and JavaScript

isplaying data in a table is everyday work for Web application developers. In this 10-minute solution, you will learn how to quickly create feature-rich tables for your JSP pages using the DisplayTag library and a little JavaScript. Specifically, the table features that we want include:

  • Alternating row colors
  • Column sorting and formatting
  • Row-grouping with subtotals for selected columns
  • Page navigation
  • Export to XML, Excel, PDF, and CSV
  • Support for standard JSP and the Expression Language (EL)
  • Row interactivity?a row is highlighted as the mouse passes over it, and if the user clicks anywhere on the row, a new request is generated that includes a parameter indicating which row was clicked.

This article includes a sample application called DisplayTagEx that displays line item details for multiple orders. (View a live demo of DisplayTagEx. A screen shot can be found in Figure 1.) Line items are grouped by order and subtotals are provided for each group. Clicking anywhere on a row takes the user to a page with more complete information about the selected item.

Figure 1. A Better Table: DisplayTagEx uses the DisplayTag library and a little JavaScript.

Listings 1 and 2 contain the source for OrderDetails.jsp and displaytagex.css, respectively.

The specific environment used to develop and deploy the article’s sample application was DisplayTag library v1.1, JDK 5.0, MyEclipse 4.1, and Tomcat 5.5. However, the steps described in this article apply to any JSP developer looking to add data tables to his or her web application.


You want to quickly add feature-rich data tables to your JSP web application.


Use the open source DisplayTag library and add in a little JavaScript.

Why Use DisplayTag?
So why use DisplayTag anyway? Why not build your data tables with JSTL and HTML? It certainly is possible to create tables this way; the problem is that it requires a large amount of drudge work. In fact, getting even the simplest table of dynamic data to display requires use of the

,

,

, , , , and tags.

Switching to a JSF-based application would help. For example, the tag from Apache’s Tomahawk library eliminates the need for the JSTL and HTML tags, and provides built-in support for column sorting. Another option would be Oracle’s recently open-sourced ADF component library, which includes the tag. It supports column sorting, page navigation, and row selection. However it does not support exporting of the table’s data. And as indicated above, these solutions have a significant drawback in that they only work in JSF-based applications.

An honorable mention should be made here of the eXtremecomponents tag, which admirably meets most of our requirements. It lacks only row grouping and subtotals.

DisplayTag Installation
To add DisplayTag capabilities to your own web application:

  1. Copy the JARs from the sample application’s DisplayTagEx/WebContent/WEB-INF/lib directory into your web application’s WEB-INF/lib directory. You can also download the latest DisplayTag libraries and dependencies from displaytag.sourceforge.net.
  2. Copy the sample application’s DisplayTagEx/WebContent/css directory into the root of your web application. Note that displaytagex.css contains all of the CSS styles described in this article.
  3. Copy the sample application’s DisplayTagEx/WebContent/images directory into the root of your web application. The files in this directory provide images for things like page navigation (first, previous, next, last) and sorting (ascending/descending).
  4. Copy the sample application’s DisplayTagEx/src/displaytag.properties file into the top-level source directory for your web application. The properties file is described in the next section.

To install and run the article’s sample application on your own app server (assumed here to be Tomcat 5):

  1. Create a directory called DisplayTagEx under Tomcat’s /webapps directory.
  2. Copy the contents of the sample application’s DisplayTagEx/WebContent/ into Tomcat’s /webapps/DisplayTagEx.
  3. Run Tomcat.
  4. Point your browser at http://localhost:8080/DisplayTagEx.

Basic Usage
Once the required libraries are installed, using the DisplayTag library is a simple three-step process:

  1. Import the tag library at the top of your JSP:
    <%@ taglib uri="http://displaytag.sf.net" prefix="display" %>
  2. Link to a CSS file:
  3. Add a tag with nested tags. For example:
        

In this example, is drawing data from the EL expression ${orderDetails}. In the article’s sample application, orderDetails is an ArrayList of OrderDetail objects that is created when the context is initialized. The table’s class attribute has been set to dataTable, which corresponds to the .dataTable style in the CSS file displaytagex.css (see Listing 2). DisplayTag automatically sets the class attribute of alternating rows to odd and even, making it easy to assign them different colors. Note that while odd and even are DisplayTag CSS class names, dataTable is a name of my own choosing.

The DisplayTag library has dozens and dozens of features, and while it is possible to configure each and every one of them for each and every table you want to display, a preferable solution is to modify displaytag.properties (see Listing 3). This file lets you to set the default value of table properties that are likely to remain the same throughout a web site. An example from the sample application’s displaytag.properties is paging.banner.placement=top. This sets the default location of the page navigation banner on top of the table. If you wish to override this property (or any other property) for a particular table, simply nest a tag within the table, as in:

  

Column Sorting and Formatting
Any column of a table can be made sortable by giving it a sortable attribute?as in . This makes the column title a hyperlink that allows the user to sort the table’s data in ascending or descending order. When the HTML for the table is generated, the column’s header cell is output as

(ascending) or

(descending). This makes it easy to add up or down arrows as CSS background images for the column header.

Note that by default, DisplayTag will only sort the data on the currently displayed page (see Page Navigation, below). To change this behavior, you can add a sort.amount=list property to displaytag.properties, as has been done in the sample application.

Table data can be formatted by adding a format=”Pattern” attribute to the column where you want to apply formatting. The Pattern attribute can be any valid java.text.MessageFormat pattern. For example, would output a date such as November 1st, 2003, in the form 11/1/03 (the actual format is locale-specific in this case).

Row Grouping and Subtotals
One of DisplayTag’s outstanding features is built-in support for row grouping and subtotals. Say you have queried a data source for order details that span a number of different orders and you want to display the results. One problem you are likely to run into is repeating information: consecutive rows representing line items from the same order will have the same customer name, order number, order date, etc. This makes it difficult to see which line items are associated with which orders.

DisplayTag will group all rows that contain repeating data in any column that sports a group attribute, as in . In the article’s sample application, I have set group=”1″ for the customer column, group=”2″ for the order number column, and group=”3″ for the order date column, which results in all three columns being grouped together (see Listing 1).

Adding a TotalTableDecorator to a table will cause the values of any column that has a total attribute to be summed up by group and output on a separate row beneath the group. DisplayTag outputs the row with a CSS class of total, making it easy to apply a special style to subtotal rows. To set the table decorator you would use . To enable subtotaling in a column, you would use .

Page Navigation
DisplayTag will add page navigation to any table with a pagesize attribute, as in . To handle the many cases associated with page navigation?only one page of data, first of many pages, middle of many pages, last of many pages, etc.?DisplayTag provides properties like paging.banner.onepage, paging.banner.first, and paging.banner.full (see Listing 3).

To illustrate how these properties are used, consider the following:

paging.banner.full=

This rather convoluted property tells DisplayTag to output a banner, similar to that shown in Figure 2, when all paging links are to be displayed.

Figure 2. Pagelinks: DisplayTagEx’s paging banner displays all the paging links.

A

is used here to set the CSS style for the banner to pagelinks. {1} is a placeholder that represents a link to the first page of data. Here it is being used as the target URL for a clickable image. {2}, {3}, and{4} are placeholders for the previous, next, and last pages, respectively. {0} is a special placeholder that outputs links to a set of numbered pages.

Exporting Data to Excel, PDF, et al.
Getting DisplayTag to export its data to CSV (comma separated value), XML, Excel, PDF, and RTF requires adding a table attribute, setting a number of configuration properties, and creating span styles for each export type.

DisplayTag will display an export banner for tables whose export attribute is set?e.g. .

As with page navigation, there are a large number of export properties to configure. Default properties should be set in the displaytag.properties file. Assuming that you want all of the supported formats to be made available to the user, the properties that are typically modified include export.banner and export.format.filename.

For example, in the sample application, I wanted to enforce right alignment and to apply the pagelinks CSS class to the list of export formats. So, in the displaytag.properties file (see Listing 3), I wrote:

export.banner=

Less obvious here is that when the export banner is rendered, each export format hyperlink is rendered within a whose class is “export format”?e.g. . Accordingly, the sample application has a CSS class associated with each format, as in:

span.excel {      background-image: url(../images/ico_file_excel.png);      background-repeat: no-repeat;      width: 16px;}

To set the filename of the exported data, modify the export.format.filename properties, as in export.pdf.filename=data.pdf.

Javascript Row Handlers
My last requirement is for rows to be highlighted as the mouse passes over them and, if the user clicks anywhere on a row, a new request is generated that includes a parameter identifying the row that was clicked. To meet this requirement, I need to throw some JavaScript into the mix.

The sample application has a JavaScript file, RowHandlers.js (see Listing 4), with a function called addRowHandlers() that adds three event handlers to each row in an HTML table:

  1. onmouseover?Saves the row’s class attribute and then changes it to a new style that has a different background color or image.
  2. onmouseout?Restores the previous class attribute.
  3. onclick?Jumps to a specified URL and includes a request parameter from the selected table row.

To add RowHandlers.js to your JSP:

  1. Link to the script in the section:
  2. Invoke addRowHandlers() in the tag’s onload attribute:

Step 2 can be translated as: when the body section of the page has loaded, call the function addRowHandlers(), which will add handlers to each row in the table whose id is row. With the handlers in place, when the user moves the mouse over a row its CSS class attribute is changed to rowMouseOver. When the mouse moves out of a row, its CSS class attribute is set back to its original value. If the user clicks on a row, they are sent to OrderDetail.jsp, where the parameter id (whose value is taken from column 0 of the clicked row) is included in the request.

In the sample application, OrderDetails.jsp (see Listing 1) uses RowHandlers.js as described above. OrderDetails.jsp also employs a little sleight of hand by placing the row id values in a hidden column. This is accomplished by setting the ‘s class and headerClass attributes to hidden, which is a CSS style whose display property is none. This is a simple but effective method for keeping data available in the request scope without having to display it to the user.

DisplayTag is an open-source tag library that makes it easy to display tables of data in JSP’s. And its applicability is almost limitless?from search results that require page navigation to product listings that benefit from column sorting to financial reports that can take advantage of numeric formatting, group subtotals, and PDF export. The list goes on and on, and I am sure that you will find uses for it in your own web application.

So what’s next? Download the sample application and try it out. After that, you can use OrderDetails.jsp as a template for your own dynamic tables. The CSS file, JavaScript file, properties file, and images included in the download can be used as is, or modified as needed to suit the style of your application.

devx-admin

devx-admin

Share the Post:
Development Project

Thrilling East Windsor Mixed-Use Development

Real estate developer James Cormier, in collaboration with a partnership, has purchased 137 acres of land in Connecticut for $1.15 million with the intention of

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India,

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner

Renesas Tech Revolution

Revolutionizing India’s Tech Sector with Renesas

Tushar Sharma, a semiconductor engineer at Renesas Electronics, met with Indian Prime Minister Narendra Modi to discuss the company’s support for India’s “Make in India” initiative. This initiative focuses on

Development Project

Thrilling East Windsor Mixed-Use Development

Real estate developer James Cormier, in collaboration with a partnership, has purchased 137 acres of land in Connecticut for $1.15 million with the intention of constructing residential and commercial buildings.

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

©2023 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.

Sitemap