`
buliedian
  • 浏览: 1222857 次
  • 性别: Icon_minigender_2
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

使用DisplayTag和JavaScript创建增强型的表格

阅读更多
Every Web developer has to tangle with tables. A new open source library, DisplayTag, can make life with tables much more organized. Find out how to combine the DisplayTag library with JavaScript to make a slick app that displays line item details.
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.
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.

http://assets.devx.com/articlefigs/15427.png

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


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 <table>, <tr>, <td>, <c:forEach>, <c:choose>, <c:when>, and <c:out> tags.

Switching to a JSF-based application would help. For example, the <t:dataTable> 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 <af:table> 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 <ec:table> 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:
    
    <link rel="stylesheet" type="text/css" href="css/displaytagex.css">
    
  3. Add a <display:table> tag with nested <display:column> tags. For example:
    
    <display:table name="${orderDetails}" class="dataTable">
    <display:column property="customerName" />
    <display:column property="productName" />
    </display:table>
    
In this example, <display:table> 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 <display:setProperty> tag within the table, as in:


<display:table … >
<display:setProperty name="paging.banner.placement" value="bottom" />
</display:table>
Column Sorting and Formatting
Any column of a table can be made sortable by giving it a sortable attribute—as in <display:column sortable="true">. 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 <th class="order1"> (ascending) or <th class="order2"> (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, <display:column format="{0,date,short}"> 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 <display:column group="1">. 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 <display:table decorator="org.displaytag.decorator.TotalTableDecorator">. To enable subtotaling in a column, you would use <display:column total="true">.

Page Navigation
DisplayTag will add page navigation to any table with a pagesize attribute, as in <display:table pagesize="16">. 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=<div class="pagelinks" align="right"><a href={1}><img 
src="images/first.gif"></a><a href={2}><img src="images/prev.gif"></a>{0}<a href={3}
><img src="images/next.gif"></a><a href={4}><img src="images/last.gif"></a></div>
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 <div> 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. <display:table export="true">.

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=<div class="pagelinks" align="right">{0}</div>
Less obvious here is that when the export banner is rendered, each export format hyperlink is rendered within a <span> whose class is "export format"—e.g. <span class="export excel">. 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 <head> section:
    
    <script src="js/RowHandlers.js" language="javascript" type="text/javascript" /></script>
    
  2. Invoke addRowHandlers() in the <body> tag's onload attribute:
    
    <body onload="addRowHandlers('row', 'rowMouseOver', 'OrderDetail.jsp', 'id', 0)">
    
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 <display:column>'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.

分享到:
评论

相关推荐

    JavaScript与displayTag标签的合作 -- 操作表头.

    以下是一个简单的示例,展示了如何使用JavaScript和displayTag实现表头的动态操作: ```html 列1" sortable="true" /&gt; 列2" sortable="true" /&gt; &lt;script src="path/to/jquery.js"&gt;&lt;/script&gt; $(document)....

    displaytag标签的使用

    总之,DisplayTag 是 JSP 开发中处理表格数据的强大工具,它的易用性和灵活性使得网页表格的开发变得更加高效和便捷。通过合理利用 DisplayTag,开发者可以将更多精力集中在业务逻辑上,而不是繁琐的页面布局和交互...

    用JavaScript操作displayTag表头操作

    JavaScript在网页动态效果和用户交互方面起着关键作用,因此,对于DisplayTag这样复杂的表格组件,理解如何通过JavaScript进行定制和控制是非常重要的。 以下是一些可能涉及的知识点: 1. **DisplayTag介绍**:...

    displaytag及使用方法

    DisplayTag是一个开源的Java库,专门用于在Web应用程序中创建复杂的表格。它提供了一系列的标签和功能,使得在JSP页面上展示数据变得更加容易和灵活。DisplayTag支持分页、排序、导出、国际化和自定义样式,是开发...

    displaytag简单项目

    DisplayTag是一个开源的...总的来说,DisplayTag项目是学习和理解如何使用DisplayTag库创建高效、功能丰富的表格应用的一个很好的起点。通过实践这个项目,你可以掌握如何在实际项目中整合和利用DisplayTag的强大功能。

    Struts2中使用displaytag标签总结

    总的来说,DisplayTag是Struts2开发中增强表格展示的强大工具,它的丰富功能和易用性使得开发者能更专注于业务逻辑,而不是繁琐的UI实现。通过深入理解和使用DisplayTag,可以提高Web应用的用户体验和开发效率。

    displaytag分页jar包和使用说明

    DisplayTag是Java Web开发中的一款强大且功能丰富的表格和分页控件库,它极大地简化了在JSP页面中处理复杂表格和实现分页的工作。这个压缩包文件包含的就是DisplayTag的相关jar包以及可能的使用说明文档,对于开发...

    displaytag-1.1.1标签库及其使用方法.rar

    4. 使用标签:在JSP中使用DisplayTag标签来创建表格。 5. 定制样式:根据需要编写CSS文件,定制表格样式。 总的来说,DisplayTag 1.1.1是一个强大且灵活的表格标签库,能够帮助开发者快速创建复杂的Web表格,提高...

    使用那个displaytag元件所需用的jar包

    DisplayTag是一个功能强大的Java Web开发库,主要用于创建表格和数据展示。它提供了许多高级特性,如分页、排序、国际化支持、导出功能等,极大地简化了开发人员在Web应用中处理复杂表格的需求。在使用DisplayTag时...

    displaytag-1.1 源码

    Displaytag是一个开源的Java库,专门用于创建复杂的表格和数据展示。在1.1版本中,它主要解决了在处理大数据分页时的问题,这使得它成为处理大量数据的理想选择,尤其是在Web应用程序中。这个源码包包含了一系列的...

    DisplayTag标签使用说明

    DisplayTag 是一个强大的开源Java库,专为Web开发设计,提供了一组标签,用于简化HTML表格的创建和操作。这个库特别适用于MVC模式的应用,它允许开发者更专注于业务逻辑而不是展示层的细节。DisplayTag 的主要目标是...

    displaytag-jar.rar_Displaytag.jar_displaytag_displaytag 1.2 jar_

    Displaytag是一个开源的Java库,专门用于创建复杂的表格布局,提供了许多高级功能,如分页、排序、国际化、导出等。在Web开发中,它作为一个JSP标签库使用,大大简化了在网页上处理表格数据的过程。"displaytag-jar....

    displaytag简明使用示例

    总结起来,DisplayTag提供了丰富的功能和灵活性,使得在JSP中创建复杂的表格变得简单。通过熟练掌握其使用方法,开发者可以高效地构建出具有排序、分页和样式定制等功能的动态表格。无论是简单的数据展示还是复杂的...

    displaytag的使用方法

    Displaytag 是一个开源的 JSP 标签库,专门用于创建数据表格,提供了一组易于使用的标签,可以实现复杂的表格功能,如分页、排序、导出等。在本文中,我们将详细讨论 Displaytag 1.1 版本的使用方法。 **一、...

    displaytag详细用法(中文问题已解决)

    DisplayTag是一个开源的Java库,专门用于创建复杂的表格展示,尤其在Web应用中十分常见。这个压缩包包含了解决DisplayTag在处理中文显示时遇到的问题,以及一个专门用于编辑.properties文件的插件,使得配置更加方便...

    JavaScript与displayTag标签的合作 -- 操作表头(二)

    7. **增强性能**:如果表格数据量很大,使用displayTag的延迟加载功能,结合JavaScript的分页处理,可以提高页面加载速度和用户体验。 8. **优化显示**:对于复杂的表头,可以使用JavaScript动态构建嵌套或分组的...

    自己整理的DisplayTag标签的使用

    为了在项目中使用DisplayTag,首先需要下载并引用其提供的`DisplayTag.jar`文件,以及依赖的Apache项目相关jar包。此外,还需要在`web.xml`中进行相应的标签库配置,具体如下: ```xml &lt;taglib-uri&gt;...

    displaytag,pager-taglib 分页包

    使用Displaytag,开发者可以快速地在网页上创建出功能丰富的表格,而无需编写大量的HTML和Java代码。以下是Displaytag的一些关键知识点: 1. **表格渲染**:Displaytag通过JSP标签来渲染表格,可以轻松地控制列宽、...

    分页组件displaytag使用笔记

    DisplayTag是一个用于创建表格、分页和导出数据的JSP标签库。它通过简化HTML表格的复杂性,提供了诸如排序、分页、格式化和国际化等特性,极大地提高了开发效率。 2. **安装与引入** 要使用DisplayTag,首先需要...

Global site tag (gtag.js) - Google Analytics