Developer

Gain functionality via the Decorator pattern and the JSTL

Enhance your Java skills with these quick Java tips. First, see how the Decorator pattern can reduce coding. Then, learn how you can overcome a limitation of the JavaServer Pages Standard Tag Library.


You're probably already using the Decorator pattern, but as with all patterns, it’s important to know why you're using it and to learn how to communicate about it with other developers.

The main reason to use the Decorator pattern—also known as the Wrapper pattern—is a need to add functionality to a class without modifying its code or disturbing its inheritance. While you may want the class to have more functionality, using the Decorator pattern means that your improved functionality version doesn’t have to reuse the existing functionality by extending the class.

Here's an example. Given an interface named Action with two methods, act1() and act2(), and a concrete version of this interface named ConcreteAction, the Decorator would be a class that implements Action and whose constructor takes an Action (usually ConcreteAction). So the code would look like Listing A.

Using the Decorator results in fewer classes than inheritance, so coding is simpler; however, it usually results in more objects, which can make debugging harder, especially since the added flexibility can introduce new areas for errors.

Another cup of Joe
  • ·        "A brief review of the EJB 2.1 specification"
    Java continues its rapid development with the EJB 2.1 specification. Take a closer look at the exciting new features available in this release.
  • ·        "Java: Not just for the server anymore?"
    Java has a somewhat deserved reputation for being a server-side-only affair. But now, the language is becoming an increasingly popular choice for embedded development as well. Don't miss this article's recent discussion posts.


Overcome jsp:include limitations with the JSTL import tag
The JavaServer Pages Standard Tag Library (JSTL) provides a standard set of custom tags, including the JSTL import tag. The import tag adds functionality to the jsp:include tag and eliminates the need to code these functions yourself.

The first additional function allows you to include content directly from other Web sites. So the following is now legal:
<c:import url="http://www.example.com/somecontent.html"/>

You can even use ftp:
<c:import url="ftp://ftp.example.com/somecontent.txt"/>

Rather than dump an imported URL straight to the page, you can store it in a variable. This is a common strategy in all the JSTL tags and increases the power of a JSP page:
<c:import url="http://www.example.com/example.inc" var="example"/>

Once this included page is stored in the example variable, you can use another taglib, such as the Jakarta String taglib, to replace all references to example.com with done.com. The JSTL import tag has a namespace of c, which stands for core and is the recommended namespace.

Editor's Picks