Extending the JSP Language

You can perform a wide variety of dynamic processing tasks including accessing databases, using enterprise services such as email and directories, and flow control with JavaBeans components in conjunction with scriptlets. One of the drawbacks of scriptlets however, is that they tend to make JSP pages more difficult to maintain. Alternatively, JSP technology provides a mechanism, called custom tags, that allows you to encapsulate dynamic functionality in objects that are accessed through extensions to the JSP language. Custom tags bring the benefits of another type of componentization to JSP pages.

For example, recall the scriptlet used to loop through and display the contents of the Duke's Bookstore shopping cart:

<% 
	Iterator i = cart.getItems().iterator();
	while (i.hasNext()) {
		ShoppingCartItem item =
			(ShoppingCartItem)i.next();
		...
%>
		<tr>
		<td align="right" bgcolor="#ffffff"> 
		<%=item.getQuantity()%>
		</td>
		...
<% 
	} 
%> 

An iterate custom tag eliminates the code logic and manages the scripting variable item that references elements in the shopping cart:

<logic:iterate id="item"
	collection="<%=cart.getItems()%>"
	<tr> 
	<td align="right" bgcolor="#ffffff"> 
	<%=item.getQuantity()%>
	</td> 
	...
</logic:iterate> 

Custom tags are packaged and distributed in a unit called a tag library. The syntax of custom tags is the same as that used for the JSP elements, namely <prefix:tag>, but for custom tags, the prefix is defined by the user of the tag library and the tag is defined by the tag developer.


From the J2EE Tutorial section on JavaServer Pages Technology by Stephanie Bodoff.

Maintained by John Loomis, last updated 31 March 2001