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.

I am not implying that you cannot currently use XML with JavaServer Pages technology. I simply prefer to wait for better tools to manage the JSP-to-XML mapping as outlined in the 1.2 specification before pursuing XML-compliant JSPs (also called JSP documents). There are, however, other ways the two technologies can be used together. See Resources for articles on using XML with JSPs.

Be sure to keep abreast of the latest JSP specification and the tools your preferred vendors provide that implement that spec’s new features, such as JSP-to-XML mapping. Apache provides Tomcat 4.0 as a reference implementation of the JSP 1.2 Specification.

Use JSP comments in most cases

Appropriate commenting seems to challenge software developers. JSPs, like other types of code, should include comments that describe complex or extraordinary functionality, the pages’ purpose, and other general information typically commented out in source code.

Since JSPs allow developers to intermix Java, JSP tags, and HTML tags in the same page, there are multiple ways to comment a JSP page. Developers should carefully consider which type of comment to employ in the page. HTML comments will be viewable in the compiled JSP’s HTML source code, and both major browsers make viewing this source easy. JSP comments, on the other hand, are not placed in the HTML document created by the JSP compilation process. These comments cannot be viewed as part of the page’s source through the browser, and they do not increase the size of the rendered page’s generated source. Java comments can also occur in a JSP inside Java scriptlet sections. These are not viewable in the browser either, but including Java comments in the JSP page violates the principle of separating Java from the HTML.

Code comments are usually meant for developers who write and maintain code. Therefore, use JSP comments unless there is a compelling reason to have the comments display in the browser upon request.

Note that you should not place sensitive data in JSP source code, not even inside JSP comments. Although the text inside JSP comments is not compiled into the source used to render the Webpage, Web servers might allow users to view JSP source code. Place sensitive data in a database, where access to the data can be controlled and monitored using triggers or other database mechanisms.

Follow HTML best practices

When Java is factored out of the JSP and into JavaBeans and custom tag handlers, the JSP consists mostly of JSP tags, including custom tags, and HTML tags. To make the JSP easier to understand and maintain, follow best practices related to HTML development.

One HTML best practice I follow: include closing tags recommended by the HTML specification even when the browsers do not require them. Most HTML generation tools will match opening tags with corresponding closing tags, but hand-typed HTML documents often lack closing tags (note that there is a small set of HTML tags that lack closing tags). Browsers usually render the page despite missing closing tags, but don’t count on the browser to work correctly when standards are violated. Some missing closing tags, such as </table>, can dramatically affect a page’s rendering in the browser. In addition, you should avoid using deprecated HTML tags, and use lowercase letters for all HTML tags.

The W3C (World Wide Web Consortium) has some resources related to HTML best practices and validation.

Utilize the JSP exception mechanism

While a thrown exception’s stack trace proves extremely useful for developers when debugging their code, it is rarely desirable to share an entire exception stack trace with the software’s users. Lengthy stack traces are not aesthetically pleasing and can increase security risks by exposing information that does not need to be released. JSPs allow developers to catch and handle exceptions in the code, resulting in more secure and aesthetically pleasing exception handling. See Resources for details on the mechanics of JSP exception handling.

Exception information is more useful if information besides the stack trace is included. JSPs can use session variables to store information about the current page and current operation being performed. Then, if an exception does occur, the exception page will be called; it will have access to both the thrown exception and the information about the original page that caused the exception. The exception page can utilize underlying Java code, in JavaBeans or EJBs, to store in the database the complete exception information, related session information, and the exception’s date and time.

To reduce the unsightly error messages printed to the screen and improve security, the exception page need only print out a simple error message and perhaps an identifying number that allows developers to locate more detailed exception information in the database. For aesthetic and security reasons, I prefer storing most of the exception information in a database or flat file rather than printing it all to the screen. Storing the exception information in a database or flat file also allows the information to be persisted even when a user exits the application. Note that during development you should print full exception information to the screen for regular testing and debugging.

Now start developing JSPs

If abused, many JSP conveniences can lead to unnecessary complexity. This article summarizes some JSP practices that allow developers to take advantage of these conveniences without triggering unnecessary complexity. By following the best practices discussed here, you will increase your software’s maintainability and reusability as well as its aesthetic qualities.

Situations might arise where the overhead of some of these recommended JSP practices is not worth the cost, such as in extremely simple applications. However, my experience is that even the simplest applications often evolve into more complex systems. In most cases, the sooner you follow best practices such as these, the better.

Dustin Marx is a senior
software engineer at Raytheon Systems Company in Aurora, Colo. He
has a bachelor’s degree in electrical engineering and a master’s
degree in business administration. He has been writing software for
more than 10 years and, for the last five years, has been
concentrating on object-oriented software using C++ and Java.
Although he typically prefers processing and database-related
development over GUI work (especially HTML pages), he has found
JavaServer Pages technology to be appealing when the practices
recommended in this article are followed.

Source: www.infoworld.com