More JSP best practices

JSP advancements ease development of standardized, highly maintainable JSP-based applications

1 2 3 Page 2
Page 2 of 3

The above approach works well when comparing any custom tag library to JSTL. If JSTL fully supports the same functionality, use the standardized JSTL tags. If JSTL tags fail to support some important features you use in these other tag libraries, there is no reason to change to JSTL. In most cases, as I described in my use of Struts and JSTL tags above, you will probably use a mixture of JSTL tags and other tag libraries.

JSTL: Final notes

See Resources for links to more details about JSTL, its advantages, and how to use JSTL in your JSPs. The Resources section also contains a link to Apache's Jakarta Standard Taglib, an open source and widely used JSTL implementation. Web server vendors have begun to deliver JSTL implementations with their Web servers, and JSTL is anticipated to be an integrated part of the final JSP 2.0 specification.

Take advantage of servlet filters

While servlet filters were actually introduced as part of the Servlet 2.3 specification, these filters benefit JSP development and maintenance as well. Because JSPs are converted into servlets and are highly coupled with servlet technology, it shouldn't be surprising that significant advancements in the servlet specification often impact JSP development.

Servlet filters are the J2EE implementation of the Intercepting Filter pattern and thus provide the advantages associated with this pattern. These advantages include better maintainability, reduced code redundancy, and greater portability. Servlet filters offer these advantages because many required services that you would normally need to add to each JSP you can instead place into a single servlet. The JSPs do not even need to be aware the filter exists. This lack of coupling between pluggable filters and JSPs means that any changes to the filters will not directly impact the JSPs themselves. You can chain filter servlets, enabling mixing and matching of different filters, each designed for specifically different purposes.

Usefulness of servlet filters in JSP Web applications

Two examples illustrate the usefulness of servlet filters in JSP-based Web applications. In many security configurations, each JSP checks the session ID or some other security credential to authenticate the JSP's caller. You can move the code for performing this check out of each JSP that makes the check and into a single servlet filter invoked before each JSP executes. Moving the redundant security code out of each JSP and into a single servlet filter significantly improves the JSPs' maintainability and portability. You likely only need to make changes or additions to security-related code in the single servlet filter and not in each JSP. If an entirely different security mechanism is chosen in the future, the servlet filter is the only piece of the system you must replace. The individual JSPs would require no changes.

In the previous "JSP Best Practices" article, I recommended storing exception information in some type of secondary storage and only providing the user with an identifier to search the storage for the entire exception trace. A servlet filter is very useful in this situation. You can configure a Web application (via the web.xml file) to automatically execute a servlet filter that logs exception information whenever the exception JSP is called. This allows a presentation-oriented exception page with all the processing and storage code placed in the intercepting filter.

The servlet specification itself lists numerous potential servlet filter uses.

Document the APIs for your JSPs

One of Java's many desirable features is its Javadoc support. Javadoc lets you quickly and easily provide Web-based documentation of your Java code. Unfortunately, the Javadoc tool does not support JSP, and the JSP specification does not call out a similar method of providing "JSP APIs."

What is the JSP API?

It would be extremely useful to quickly identify some JSP aspects without scouring the JSP code itself. For example, you need to know which variables are bound to session, request, or application scope, and which of these scopes they are bound to. Another example of useful JSP API information is denoting in JSP segments which variables they require the calling JSP to have declared and defined when including them.

The JSP specifications do not address the issue of documenting JSP APIs. The JSP 1.x Code Convention document from Sun (see Resources) discusses putting comments at the top of JSPs with information such as author, copyright, and description, but I like to document my JSPs' expected inputs more thoroughly.

Because the specification does not address this, there is no standard for commenting this type of JSP API information. One approach might be to use scriptlets and enclose Javadoc-style comments (/** javadoc comment */) in them. Although I typically do not place scriptlets in my JSPs, this is the easiest way to keep these comments on the server side only when using JSP documents. It is not a good idea to expose your JSP APIs to clients by using XML/HTML-style comments for this information.

I am aware of two freely available products for documenting your JSPs. JspDoc is available through Another tool with a similar name is JSPDoc, available at Open Source Development Network (OSDN)'s (See Resources for more detailed information about these two products.) I present a brief summary of each product here.

JspDoc (SourceForge)

Available through SourceForge, the JspDoc tool generates Javadoc-like documentation pages for JSPs. This documentation generation is enabled by placing XML-compliant tags within Javadoc-style comments (/** */) that are in turn placed within JSP page scriptlet tags (<% %>). A drawback is that this tool only supports JSP pages, though support for JSP documents is on the planned extensions list.

This tool also provides a utility for converting JSP pages ("classic") to JSP documents ("new"). Because I write JSP documents to begin with, I have not used this extra utility, but it might benefit those wishing to migrate JSP pages to JSP documents. Another utility converts JSP documents to JSP pages.

JSPDoc (

Listed as JSP Documentation Generator on the site, this tool extracts information directly from your JSPs to build Javadoc-like Web-based documentation pages. One of this tool's strengths is its ability to integrate the generated JSP documentation with Javadoc-generated documentation for Java classes. One drawback is that the expected comment structure for generating documentation pages is fairly rigid. This special syntax uses Javadoc delimiters (/** */), but does not recognize the special significance of the @ symbol, which is meaningful in standard Javadoc. This is an issue for the product's to-do list. Another drawback for me is that this tool does not support XML-compliant JSP documents, but instead requires <% %> syntax use. This product is available under the Mozilla public license.

JSP documentation generation for JSP documents

Because neither JspDoc nor JSPDoc currently support JSP documents, I take advantage of JSP documents' XML-compliance to perform Javadoc-like documentation generation. Using an XSLT stylesheet, you can easily create HTML-based pages documenting the XML-compliant JSP documents. No custom parsing is required because any of the standard translator tools (such as Xalan) will handle this process when the source document is a valid XML document. See the "JSP Documentation with XSLT" sidebar for such a stylesheet example.

Precompile your JSPs, even in development

When you execute a JSP by typing its URL into the browser, the JSP goes through much processing before being rendered to the browser as HTML. Because of all this processing, JSPs take considerably longer to execute the first time they are accessed than they do on later accesses. While most developers understand the importance of compiling these JSPs before making them available to the public, it is also useful in development to precompile JSPs before rendering them as HTML.

You can include the precompilation process in the regular code build, and compile JSPs at the same time as their associated JavaBeans, custom tag handler classes, and other associated classes and servlets. This lets you run a single build and keep most of the waiting time confined to one period. Because developers are often distracted as they wait for compilation, it can be advantageous to do all the compilation at once rather than compile each JSP as it's requested.

Precompilation can catch parser problems and other translation-time problems of pages that typically require several steps to reach. This is advantageous because it prevents the developer from navigating through multiple pages to get to the point where the relevant page is requested. If you use JSP documents, the precompilation step typically verifies that the JSP document is well formed.

Another advantage of precompilation is that you can include your JSPs' compiled versions in the Web archive (war) file rather than delivering the actual JSP source code in the war file. When JSPs are precompiled and translated for inclusion in the war file, they are included as .class files with vendor-specific naming conventions.

JSP precompilation is available with most modern Java 2 Platform, Enterprise Edition (J2EE)/Java IDEs. The major Web servers also support JSP precompilation, though they typically support it with nonstandard commands or interfaces. Most Web servers provide a command line-based JSP precompiler that you can integrate with scripted builds.

Organize files and directories

The following are additional techniques that make JSP development and maintenance easier and more efficient:

  • Organize the Web context root directory
  • Organize the WEB-INF directory with appropriate subdirectories
  • Identify JSP fragments with the .jspf extension
  • Use IDE, Ant, or other automated tools

Some of these techniques can benefit from the use of coding conventions as described earlier in this article.

Organize the Web context root directory

You can build Web applications by putting nearly all the Web application's content files directly in the Web context root directory. This is the directory in which the WEB-INF subdirectory normally resides. I recommend organizing this directory with subdirectories such as a jsp directory, an html directory, a css directory, an images directory, and so forth. For the simplest applications, this organization is probably more hassle than it's worth, but it eases comprehension and maintainability of large Web applications.

Organize the WEB-INF directory

Tag libraries are a valuable resource in JSP development. Large Web applications might consist of several tag libraries such as JSTL tag libaries, Struts tag libraries, and other tag libraries. Instead of inundating the WEB-INF directory with tag library descriptors, I prefer to create a tld subdirectory under WEB-INF and place the tag library descriptors there. You can do this to existing Web applications without harming the existing JSPs as long as the mapping in the web.xml file is edited to account for the new tld subdirectory. The web.xml file, the classes directory, and the lib directory are standard components in the WEB-INF directory. Moving the tag library descriptor files into their own directories reduces WEB-INF directory clutter.

Identify JSP segments with the .jspf extension

Known as JSP segments in more recent JSP specifications and JSP fragments in older specification versions, .jspf files are incomplete JSPs designed for inclusion in an encompassing JSP. The JSP specification encourages the use of naming conventions to help differentiate between outer (or top-level) JSPs and these JSP fragments/segments. Although the specification does not require it, the most common method of making this differentiation is to name complete and top-level JSPs with the traditional .jsp extension and the JSP fragments/segments with the .jspf extension. I also suggest keeping top-level JSPs in a separate subdirectory from the JSP fragments.

Use IDE, Ant, or other automated tools

IDEs can speed development and deployment times and reduce typos and other minor errors. Numerous IDEs are now available with J2EE development tools and wizards. These IDEs are being delivered with integrated frameworks such as Struts and JSTL tag libraries.

Ant is the defacto standard for building and deploying Java and J2EE applications. Ant allows enough flexibility to build and deploy virtually anything you want, but also provides specific support for building and deploying war and ear files. Many IDEs now have Ant-integration support. When I don't have access to an IDE, I consider Ant indispensable. Other tools that automate the building and deployment process can provide the same advantages of Ant, but Ant's most significant advantage may be its cost (freely available as open source) and its wide support and userbase.

I also want to mention Apache Maven as a useful product to consider for total Java project management.

Reconsider nonspecification-compliant features

Web servers occasionally provide vendor-specific features useful in production because they improve performance, increase security, or offer other advantages. In some cases, using these vendor-specific features is justified because the advantages outweigh the risks. However, it is important to be aware of the risks associated with vendor-specific features and to choose specification-compliant features over vendor-specific ones when their benefits are roughly equal. Keep in mind that not all features are specifically called out in the specification and, in that case, any vendor's implementation will be proprietary.

1 2 3 Page 2
Page 2 of 3