http://www.developer.com/

Back to article

Enrich Your Applications with JSP Components


July 26, 2005

JavaServer Pages, commonly referred to as JSP, has been a core technology in the J2EE world for years. Prior to the introduction of JSP, Java developers built dynamic Web pages by writing Java Servlets that spooled out HTML code. With the arrival of JSP, the focus of Web page development returned to HTML markup, which could be enhanced with small scriptlets of Java to take care of the dynamic portions of the page. A subsequent release of the JSP specification introduced support for custom JSP tags. Tag libraries provide a way to extend the functionality of JSP. JSP tag libraries encapsulate display logic in Java libraries that markup specialists can invoke as needed by inserting the tags into their JSP files. Custom tags further reduce the amount of Java needed in JSP and provide a mechanism to add complex visual components with ease.

In recent years, other presentation technologies have begun to challenge JSP as the presentation language of choice. Most notable is the JavaServer Faces, or JSF, specification. JSF is a standards-based technology that promises a component-driven approach to development. Still, JSP technology is a more mature offering and has a wider developer following than its rivals. For example, the market for JSF visual components is still rather limited, although there are many open-source and commercial JSP tag libraries available for use today. In this article, I will showcase a few open-source projects that provide JSP tag libraries to enable you to add rich, functional Web components with cross-browser support.

This article will not provide a tutorial on JSP or JSP tag libraries. There are many resources available for learning these technologies if you're not already familiar with them. Also, an in-depth tutorial of the projects below has been avoided. All three are well-documented and provide on-site demos to help you learn how to use their libraries to meet common application requirements. Hopefully, this article will pique your interest enough that you will dig deeper on your own.

Tabular Data with DisplayTag

The HTML table is one of the most common constructs in a Web application. Besides their usefulness when laying out components on a page, tables can display rows of data from a collection. Compared to the capabilities a desktop application might offer when viewing tabular data, the HTML table delivers very little in terms of functionality. Enter a project called DisplayTag. Using DisplayTag, you can easily add table components with a wide array of useful features. These features include, but are not limited to, column sorting, pagination for large record sets, and a logical grouping of data.

All of the projects covered in this article require similar steps when adding them to your applications: Add a Java library (a .jar file) that contains the custom tag logic (and any third-party libraries they might be dependent upon), then add the tag library descriptor file (a .tld file) to the classpath. Once you've added these files from the DisplayTag distribution, it's likely that there's not much more you need to do. Displaytag requires a Java List object as input. As opposed to the scriplet code usually required to iterate through the data, DisplayTag conceals all of this logic. Instead, there are a number of tag attributes that can be used to customize a table's display. In addition to functionality previously mentioned, DisplayTag can provide links to export table data to another format. By default, DisplayTag is set up to export data to a comma-separated (csv), spreadsheet, or (Extensible Markup Language (XML) format. With an additional third-party (and open-source) Java library from iText library, you can export the data into PDF format.

To demonstrate the use of the JSP tags discussed in this article, I have created a small, single-page application that displays employee data in a variety of ways. To generate some sample data, I create a Java List object with Employee objects in a Servlet init method. In a real-world application, this data would probably come from the database.

Here is the JSP tag markup used to add a DisplayTag table, followed by a snapshot of its output:

<display:table name="applicationScope.employeeList"
               defaultsort="1" export="true"
               pagesize="4"
               decorator="examples.SampleWrapper">
<display:column property="empId" title="ID"
                sortable="true"
                headerClass="sortable"/>
<display:column property="department"
                title="Department" group="1"
                sortable="true"
                headerClass="sortable"
                width="20%"/>
<display:column property="lastName"
                title="Last Name"
                sortable="true"
                headerClass="sortable" />
<display:column property="firstName"
                title="First Name"
                sortable="true"
                headerClass="sortable" />
<display:column property="email"
                title="Email" sortable="true"
                headerClass="sortable" autolink="true" />
<display:column property="hireDate"
                title="Date Hired"
                sortable="true"
                headerClass="sortable" />
<display:setProperty name="export.pdf"
                     value="true"/>
</display:table>



Click here for a larger image.

Sample DisplayTag Table

You can probably figure out what task most of these tag attributes perform. In this table, every column can be use to sort the data, with the first column as the default 'sort by' column. It will only display four rows of data at a time, leaving you to page through the rest of the data. Notice the formatted 'Date Hired' column. DisplayTag allows you to create a Decorator object that converts your data at runtime into the preferred format. To alter other visual characteristics (color, font, and so forth), you can do so by defining them in a Cascading Style Sheet (CSS) file.

Analytical Charts with Cewolf

Last year, I wrote an article that introduced a project called Cewolf. Cewolf provides JSP tags to display charts in web applications. Actually, what Cewolf provides is a layer of functionality on top of another open-source project called JFreeChart, which actually generates the chart graphics. To incorporate Cewolf charts into your application, there will probably be a little more work involved than was needed for a DisplayTag table. To create a chart, JFreeChart uses an object that implements an interface called Dataset. Cewolf requires you as the developer to create a Java object that implements an interface called DatasetProducer. Essentially, a Cewolf DatasetProducer supplies input to a JFreeChart Dataset that is used to create various types of charts. Once a chart is generated, the DatasetProducer returns the image to your JSP page for display.

After you have added the necessary tag libraries and descriptor file, and you've implemented one or more DatasetProducers, you're ready to add the Cewolf JSP tags. For purposes of demonstration, I created two DatasetProducer classes, one that handles employee data grouped by department and another that groups employees by department and year hired, called EmployeesByDept and EmployeesByDeptAndYear respectively. Then, I added the following Cewolf tag markup for the charts:

<table border="0" align="center" >
   <tr>
      <td>
         <!--Example 1 : Simple 3D bar chart showing employees
                         by department-->
         <cewolf:chart id="pieChart"
                       type="pie3d"
                       title="# By Department"
                       showlegend="true">
            <cewolf:data>
               <cewolf:producer id="pieChartView" />
            </cewolf:data>
            <cewolf:colorpaint color="#FFFFFF"/>
            </cewolf:chart>
            <cewolf:img chartid="pieChart"
                        renderer="cewolf"
                        border="0"
                        width="285"
                        height="250"/>
      </td>
      <td>
         <!--Example 2 : 3D Bar Chart showing employees by
                         department and year hired.-->
         <cewolf:chart id="barChart"
                       type="horizontalBar3D"
                       title="# By Department/Year Hired"
                       showlegend="true"
                xaxislabel="Employees" yaxislabel="Year Hired">
         <cewolf:data>
            <cewolf:producer id="barChartView" />
         </cewolf:data>
         <cewolf:colorpaint color="#FFFFFF"/>
         </cewolf:chart>
         <cewolf:img chartid="barChart"
                     renderer="cewolf"
                     border="0"
                     width="290"
                     height="290"/>
      </td>
   </tr>
</table>

Below are the two charts that appear as a result. The first displays the simpler of the two charts: a pie chart displaying employees grouped by department. The bar chart beside it adds a second category for year hired. Each chart is capable of showing a legend and descriptive chart labels.



Click here for a larger image.

Sample charts

Rich Components with pragmaticObjects

Making the leap from the world of desktop applications to web-based applications usually means a sacrifice in terms of functionality. Components such as tabbed panes, context-sensitive menus, and tree menus are thick client standards, but it is difficult to duplicate these objects in a web environment. The last project we will look at, pragmaticObjects, provides a number of web components, made available through a set of JSP tags, to rival the look and capability of desktop components. Almost every Web application requires some sort of navigation between pages. Typically, accomplished with the standard HTML hyperlink, there is significant room for improvement in this area. The current set of components that pragmaticObjects provides include an outlookBar similar to what you might see in Microsoft Outlook, a controlPanel that mimics a Windows control panel, and a tree capable of providing context-sensitive menus for each of its nodes.

The pragmaticObjects Web site demos each of these components. To use them, download and add the pragmatic-controls.tld and pragmatic-controls.jar to your application. In addition to these files, you might require one or more XML files (the downloadable demo programs include samples of each of these) that can be used to configure the components. Public Java APIs are available if there is a need to modify the components at runtime.

We will add two components from this project to the sample application. First, a frame is added to display an outlookBar. This component is configured using the same outlook-bar.xml configuration file provided with the demo. Below is an image of what this outlook bar looks like. Clicking on any of the tabbed panes will bring that pane to the forefront. Each element within a pane will lead you to the URL that you specify.

Sample Outlook Bar

The result is a rich-looking component that consumes very little screen real estate. This component is configured to access a resource file, which allows you to support internationlization. The JSP tag markup contained in outlookMenu.jsp is listed below. With all pragmatic components, when the tag is executed, it will look for an attribute by that name in the current HttpSession. If no session variable exists by that name, it will produce one.

<html>
   <pragmatic:outlookBar configXmlPath="WEB-INF/outlook-bar.xml"
                         sessionName="XYZ"
                         resourceBundle="OutlookBar"
                         language="<%= (String)
                            session.getAttribute("LANG")%>"/>
</html>

As mentioned previously, a powerful capability of these components is that you can create them at runtime using their Java APIs. To demonstrate, a tree component will be added programmatically. Have a look at the following Java class called EmployeeTree. It contains a single method called buildTree that builds a tree component based upon the same employee list that we used for the DisplayTag table. We obtain this list from the ServletContext, pass it to the method that builds, then returns, a tree menu. The resulting tree will display all employees, grouped by their respective departments. In addition, the tree component has the ability to provide context-sensitive menus. By right-clicking a node, you can provide users with a list of menu items. We create two context menus, one for employee nodes and another for nodes representing a department, by referencing a context-menu.xml configuration file. The buildTree method assigns these context menus to the correct node. The following scriplet in our JSP creates the tree and the context menus that go along with it:

<%
if (session.getAttribute("tree") == null) {
   //Load from our defined XML file using pragmaticObjects API
   //because menu items won't change...
   ContextMenu empMenu =
      new ContextMenu().loadFromXml(application.getRealPath(
         "WEB-INF/contextMenu.xml"));
   List employeeList =
      (List) application.getAttribute("employeeList");
   //Our defined method to conceal the tree-building logic...
   Tree tree = empTree.buildTree(employeeList);
   //Add menus to session...
   session.setAttribute("tree",tree);
   session.setAttribute("empMenu",empMenu);
}
%>

Finally, you add the necessary JSP tags to display the pragmaticObjects tree component as shown below. Main.jsp contains all of the JSP tags that I've covered in this article, with the exception of the pragmaticObjects outlookBar that you placed in a separate frame.

<table width="100%" border="0">
   <tr>
      <td valign="top" width="15%">
         <pragmatic:tree-body treeConfigXmlPath="WEB-INF/tree.xml"
                              treeSessionName="tree"
        resourceBundle="TreeMenu" language="<%=
           (String) session.getAttribute("LANG")%>"
           contextMenuConfigXmlPath="WEB-INF/contextMenu.xml"
           contextMenuSessionName="empMenu"/>
      </td>

Sample Tree Component



Click here for a larger image.

Putting it all together...

Conclusion

If you're developing JSP applications, I encourage you to take a look at the projects mentioned here in greater detail. Each one of them prove that JSP tags can provide a fast and easy way to enliven your Web applications.

About the Author

Michael Klaene is a Senior Consultant with Sogeti LLC. He has spent over 7 years in IT, specializing in J2EE and Oracle analysis and development.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date