JSP best practices

Follow these tips for reusable and easily maintainable JavaServer Pages

JavaServer Pages (JSPs) technology is an extension of Java servlet technology and combines HTML and Java code into a single file. While Java servlet technology focuses on Java classes capable of generating HTML output with PrintWriter.println() statements, JSP technology abstracts this concept to a higher level. With JavaServer Pages, a Web developer can write static HTML pages and simply add Java code in those sections of the page that need to be dynamically generated. While this flexibility enables rapid development of simple Web applications, it can be abused, resulting in unnecessarily complex applications that are difficult to maintain, reuse, and enhance.

To avoid needlessly complex applications, follow the practices I present in this article:

  1. Separate HTML from Java
  2. Place business logic in JavaBeans
  3. Factor general behavior out of custom tag handler classes
  4. Favor HTML in Java handler classes over Java in JSPs
  5. Use an appropriate inclusion mechanism
  6. Use a JSP template mechanism
  7. Use stylesheets
  8. Use the MVC pattern
  9. Use available custom tag libraries
  10. Determine the appropriate level of XML compliance
  11. Use JSP comments in most cases
  12. Follow HTML best practices
  13. Utilize the JSP exception mechanism

These tips will help you write JSPs that are reusable and easy to maintain.

Separate HTML from Java

It can be tempting to throw all Java and HTML code necessary for a Webpage into a single JSP file. In simple system development, such an approach makes it easy for someone new to the system to locate all relevant code in one place and understand how it all interacts. However, this approach becomes burdensome and costly when the application grows more complex and more developers become involved.

Combining HTML and Java in the same source code can make the code significantly less readable. To enhance software readability, developers often use indentation; but mixing HTML and Java scriptlets in the same file can make useful indentation extremely difficult to maintain.

Many Web development methodologies and architectures now emphasize the separation of HTML from Java code so different developers can focus on their strengths. Properly separating Java and HTML, including HTML-like JSP tags and custom tags, allows Web designers and HTML coders to work on the HTML (presentation) aspects, while Java developers work on the application's Java (processing logic) portions. Java developers focus on business logic as they implement the behavior behind the custom tags; Web designers then use these custom tags just as they use ordinary HTML tags.

Applications with Java properly separated from HTML are more reusable because the Java components are not tied to a Web browser and can be used by other parts of the application. In addition, maintainability is enhanced because of the increased modularization that comes from Java/HTML separation.

Placing business logic in JavaBeans also promotes stronger applications. I'll explain how next.

Place business logic in JavaBeans

Java code included directly inside a JSP is not as readily accessible to other JSPs as Java code contained within a JavaBean. Common behavior and business logic placed in JavaBeans can not only be used by other JSPs but also by other portions of the application. That is because JavaBeans are merely Java classes that satisfy some basic conventions (such as a constructor with no arguments and public get/set methods for private data members) and can be used as any other Java class. Note that Enterprise JavaBeans (EJBs) are also useful for storing behaviors and data common to all components of the application.

Factor general behavior out of custom tag handler classes

Java classes known as custom tag handlers implement custom tags. Unlike JavaBeans, custom tag handler classes are not readily used like ordinary Java utility classes. Instead, custom tag handler classes implement specific interfaces -- or extend classes that provide these interfaces' basic implementations. Because they are not readily reused outside JSPs, custom tag handlers should contain only specific behavior that would not be useful outside that custom tag -- that is, outside the JSP. Custom tags often require support for common behaviors or business logic and can utilize JavaBeans or EJBs that perform those common behaviors.

Favor HTML in Java handler classes over Java in JSPs

Sometimes cleanly separating HTML, JSP tags, and HTML-like custom tags from Java requires unnecessarily convoluted code. In these cases, you either include Java scriptlets and expressions in the JSP or put some HTML code in the Java tag handler class. I'd rather see a small amount of HTML code in the Java class than see Java, such as scriptlets and expressions, in the JSP. Since custom tag handlers are specific to the custom tags they implement (and not reusable outside JSPs), placing necessary HTML there is not troublesome. Sun's Java 2 Platform, Enterprise Edition (J2EE) Blueprints documentation discusses this issue further.

There are exceptions to this standard: if including one or two lines of Java code as scriptlets in the JSP solves the same problem that would require many more lines of HTML in the Java handler class, allowing Java code to exist in the JSP page might be prudent.

Use an appropriate inclusion mechanism

It is rarely good design to reproduce code commonly used by different application pieces each time another piece of that application needs that functionality. Factoring common JSP or HTML code out of multiple pages and into a single file improves maintainability (you need to make changes in only one location) and reusability.

Two JSP include mechanisms reduce code redundancy and promote reusability; to ensure that you use the appropriate include mechanism, it is important to know the differences between the two. Generally, I use the include directive unless I can justify a need for the include action. Question 7 in the Blueprints' "Web Tier" section provides a good resource for understanding the differences between the two include mechanisms and determining which to use in a particular situation.

Include directive

A JSP's include directive includes the content of a specified file in that JSP. Use the include mechanism for situations when text, such as ASCII or HTML, needs to be included in multiple JSPs. For example, I commonly use the include directive to include footer information, such as company name or copyright date, on every JSP in a company's application.

Since you include the content of any file specified by the include directive in the calling JSP before it compiles, variables and other values specified in the calling JSP can also be utilized in the included content. However, I try not to rely on variables defined in the calling JSP, since this dependency reduces the included file's reusability.

Include action

The include action executes the specified JSP first and then places the generated response in the calling JSP. Because the include action includes the generated response rather than the source content itself, variables and other values specified in the calling JSP are not available to the page included with the include action.

One disadvantage of the include action as currently implemented by the JSP implementations with which I am familiar relates to the flush="true" attribute. In the JSP implementations I have used, this attribute is required and must be set to true. The true value indicates that the buffer will always flush before a target page specified by the include action executes. This can prove problematic if the forward mechanism is invoked either explicitly or implicitly later in the JSP. In the recently released JSP specification (1.2), however, the include action's flush attribute can be set to false. Tomcat 4.0 provides a reference implementation of this specification and supports this new include action argument.

Use a JSP template mechanism

A template mechanism allows for a common file to control Webpage, or JSP, layout. Then, when you want to change the layout, you need to modify only one file, and all the other pages will reflect the layout change. This doesn't just make for more maintainable code; using templates to control layout also makes Webpages more aesthetically pleasing to users who see consistent layouts for all an application's pages.

I use Struts' custom tag template library as a template mechanism. David Geary's article "JSP Templates" provides a good starting point for looking at using templates with your JSPs.

Use stylesheets

Just as templates enable developers to place layout control in a single location, stylesheets enable developers to place appearance control in a single location. I use Cascading Style Sheets (CSS) to control such items as font families, font sizes, and table characteristics. Like templates, stylesheets allow the developer to make changes in one location; those changes immediately reflect on all appropriate pages, resulting in increased maintainability and consistent appearance to users.

Use the MVC pattern

While other design patterns can be used effectively with JSPs, I often use the Model-View-Controller (MVC) architecture with JSP technology. MVC enables the development of applications that are easier to create, test, maintain, and enhance. In JSP terminology, implementation of an MVC architecture is often referred to as Model 2 (from an early JSP specification). The J2EE Blueprints samples are based on MVC.

See "E++: A Pattern Language for J2EE Applications, Part 1" by Bin Yang, and "Understanding JavaServer Pages Model 2 Architecture" by Govind Seshadri, for more information on JSPs and MVC.

Struts

Struts is an open source MVC implementation (it's a Jakarta subproject available through the Apache license) that provides base controller functionality that you can extend and enhance in your own applications. The base controller is implemented as a Java servlet, and its configuration is controlled by an XML file called struts-config.xml. When a Struts-based JSP Web application is created correctly, most changes in flow control are made in the struts-config.xml file rather than in the code itself.

Implementing an application that is MVC-compliant involves extra initial effort, but the investment in time up front is worth the rewards of more maintainable and reusable code. Plus, Struts significantly reduces the preliminary work involved in implementing MVC.

Besides supporting MVC implementations, Struts also provides some valuable custom tag libraries, such as the template tag library mentioned previously. The logic tag library has custom tags for iteration and tags for if-then-else structures. The HTML tag library features many useful custom tags, including custom tags for FORM tags and form item tags used in Struts' form handling and validation. See the Struts documentation for more details on these libraries and other Struts custom tag libraries. I'll discuss the advantages of using these libraries next.

Use available custom tag libraries

Why should developers spend time reinventing the wheel and worrying about testing and debugging when custom tag libraries are readily available for many different purposes? Some vendors provide custom tag libraries to their customers for free or for individual purchase, but many custom tags can be found online. Resources provides a good starting point for locating potentially useful tag libraries.

While these third-party custom tag libraries occasionally have bugs, most likely such problems will be discovered, since many developers use these libraries and test them in their own applications. Also, many custom tags are open source, so you can edit them to meet your needs.

I find it well worth my time to keep informed of available custom tags, since these libraries often provide functionality common to most Web applications. While learning about available custom tag libraries requires a small time investment, reusing already-available custom tags saves the time of writing, testing, and debugging my own custom tags. As mentioned above, many tag libraries are also open source; in these cases, I can readily adapt general behavior to my specific project's situation.

Determine the appropriate level of XML compliance

Most JSP developers use shorthand syntax for JSP tags rather than XML syntax. This is partially evidenced by Sun's JavaServer Pages Syntax Reference, which lists only the tags' shorthand form.

An advantage to using a 100 percent XML-compliant JSP, including syntax for JSP tags, is that XML validation tools can validate the JSP. XML tools can validate the JSP against a DTD (document type definition) that enforces standard JSP syntax rules.

However, at present writing and maintaining JSPs with XML tag syntax often involves far more effort than the rewards justify. As tools are developed that automatically convert shorthand syntax to XML syntax, the benefits of XML-compliant JSPs will likely make the reduced effort worthwhile. I have waited for the JSP specification and its implementations to mature in relation to XML-compliant JSPs before fully utilizing XML-compliant tags. See the sidebar below, "XML in the JSP Specifications," for more information on how XML compliance is handled in the latest JSP specification.

1 2 Page
Join the discussion
Be the first to comment on this article. Our Commenting Policies
See more