JavaServer Pages

 

 


Contents

  1. Overview
  2. DateApp Example
  3. Bookstore Example
  4. Life Cycle
  5. Compilation
  6. Execution
  7. Initializing
  8. Static Content
  9. Dynamic Content
  10. Using Objects
  11. Scripting Elements
  12. Including Content
  13. Transferring Control
  14. Param Element
  15. Including an Applet
  16. Extending

 


Overview

JavaServer Pages (JSP) mix together HTML, SVG, WML, and XML with JSP elements, directives and scriptlets.

 

Elements, Directives, and Scriptlets

<%@ page ... %> Import classes and set the content type returned by the page.
jsp:useBean Element that creates an object containing a collection of locales and initializes a variable that points to that object.
<% ... %> Scriptlets that retrieve the value of the locale request parameter, iterate over a collection of locale names, and conditionally insert HTML text into the output.
<%= ... %> Expressions that insert the value of the locale name into the response.
jsp:include Element that sends a request to another page (date.jsp) and includes the response in the response from the calling page.

 


DateApp Example

  • If it is not running, start the J2EE server

  • Go to...

    $SRC_HOME/examples
    ...and build the example by executing...

    ant date

  • Start the deploytool, and configure a J2EE app called DateApp.

    1. Select FileNew --> Application.

    2. In the file chooser, navigate to:

      $SRC_HOME/examples/src/web/date.

    3. In the File Name field, enter DateApp.

    4. Click New Application.

    5. Click OK.

  • Create the WAR and add the Web components to the DateApp app.

    1. Select FileNew --> Web Component.

    2. Select DateApp from the Create New WAR File In Application combo box.

    3. Enter DateWAR in the WAR Display Name field.

    4. Click Edit.

    5. Navigate to...
      $SRC_HOME/examples/build/web/date
      ...and select index.jsp, date.jsp, MyDate.class, and MyLocales.class.

    6. Click Add, then Finish.

    7. Click Next.

    8. Click JSP In The Web Component radio button, and then click Next.

    9. Select index.jsp from the JSP Filename combo box. Click Finish.

  • Enter the context root.

    1. Select DateApp.

    2. Select the Web Context tab.

    3. Enter date.

  • Deploy the app.

    1. Select ToolsDeploy.

    2. Click Finish.

  • Pull up the app in a browser:

    http://www.setgetweb.com:8000/DateApp

You will see a combo box whose entries are locales. Select a locale and click Get Date. You will see the date expressed in a manner appropriate for that locale.

 


The Bookstore Example

Here is the code:

 

Function JSP Pages
Enter the bookstore bookstore.jsp
Create the bookstore banner banner.jsp
Browse the books offered for sale catalog.jsp
Put a book in a shopping cart catalog.jsp
bookdetails.jsp
Get detailed information on a specific book bookdetails.jsp
Display the shopping cart showcart.jsp
Remove one or more books from the shopping cart showcart.jsp
Buy the books in the shopping cart cashier.jsp
Receive an acknowledgement for the purchase receipt.jsp

The data for the bookstore app is still maintained in a database. However, two changes are made to the database helper object database.BookDB.

  • The database helper object is rewritten to conform to JavaBeans component design patterns. This change is made so that JSP pages can access the helper object using JSP language elements specific to JavaBeans components.

  • Instead of accessing the bookstore database directly, the helper object goes through an enterprise bean. The advantage of using an enterprise bean is that the helper object is no longer responsible for connecting to the database; this job is taken over by the enterprise bean. Furthermore, because the EJB container maintains the pool of database connections, an enterprise bean can get a connection quicker than the helper object can. The relevant interfaces and classes for the enterprise bean are the database.BookDBEJBHome home interface, database.BookDBEJB remote interface, and the database.BookDBEJBImpl implementation class, which contains all the JDBC calls to the database.

The implementation of the database helper object follows. The bean has two instance variables: the current book and a reference to the database enterprise bean.

public class BookDB {
   private String bookId = "0";
   private BookDBEJB database = null;

   public BookDB () throws Exception {
   }
   public void setBookId(String bookId) {
      this.bookId = bookId;
   }
   public void setDatabase(BookDBEJB database) {
      this.database = database;
   }
   public BookDetails getBookDetails() 
      throws Exception {
      try {
         return (BookDetails)database.
            getBookDetails(bookId);
      } catch (BookNotFoundException ex) {
         throw ex;
      } 
   }
   ...
}

Finally, this version of the example contains an applet to generate a dynamic digital clock in the banner.

To build, deploy, and run the example:

  • Go to...

    $SRC_HOME/examples
    ...and execute...

    ant bookstore2

  • Start the j2ee server.

  • Start deploytool.

  • Start the Cloudscape database by executing cloudscape -start.

  • If you have not already created the bookstore database, run ant create-web-db.

  • Create a J2EE app called Bookstore2App.

    1. Select FileNew -->Application.

    2. In the file chooser, navigate to:

      $SRC_HOME/examples/src/web/bookstore2

    3. In the File Name field, enter Bookstore2App.

    4. Click New Application.

    5. Click OK.

  • Add the Bookstore2WAR WAR to the Bookstore2App app.

    1. Select FileAdd --> Web WAR.

    2. In the Add Web WAR dialog box, navigate to

      $SRC_HOME/examples/build/web/bookstore2. Select bookstore2.war. Click Add Web WAR.

  • Add the BookDBEJB enterprise bean to the app.

    1. Select FileNew Enterprise Bean.

    2. Select Bookstore2App from the Create New JAR File In Application combo box.

    3. Type BookDBJAR in the JAR Display Name field.

    4. Click Edit to add the content files...

    5. In the Edit Archive Contents dialog box, navigate to the

      $SRC_HOME/examples/build/web/ejb directory
      ...and add the database and exception packages. Click Next.

    6. Choose Session and Stateless for the Bean Type.

    7. Select database.BookDBEJBImpl for Enterprise Bean Class.

    8. In the Remote Interfaces box, select database.BookDBEJBHome for Remote Home Interface and database.BookDBEJB for Remote Interface.

    9. Enter BookDBEJB for Enterprise Bean Name.

    10. Click Next and then click Finish.

  • Add a resource reference for the Cloudscape database to the BookDBEJB bean.

    1. Select the BookDBEJB enterprise bean.

    2. Select the Resource Refs tab.

    3. Click Add.

    4. Select javax.sql.DataSource from the Type column.

    5. Enter jdbc/BookDB in the Coded Name field.

  • Save BookDBJAR.

    1. Select BookDBJAR.

    2. Select FileSave As.

    3. Navigate to the directory examples/build/web/ejb.

    4. Enter bookDB.jar in the File Name field.

    5. Click Save EJB JAR As.

  • Add a reference to the enterprise bean BookDBEJB.

    1. Select Bookstore2WAR.

    2. Select the EJB Refs tab.

    3. Click Add.

    4. Enter ejb/BookDBEJB in the Coded Name column.

    5. Select Session in the Type column.

    6. Select Remote in the Interfaces column.

    7. Enter database.BookDBEJBHome in the Home Interface column.

    8. Enter database.BookDBEJB in the Local/Remote Interface column.

  • Specify the JNDI Names.

    1. Select Bookstore2App.

    2. In the Application table, locate the EJB component and enter BookDBEJB in the JNDI Name column.

    3. In the References table, locate the EJB Ref and enter BookDBEJB in the JNDI Name column.

    4. In the References table, locate the Resource component and enter jdbc/Cloudscape in the JNDI Name column.

  • Enter the context root.

    1. Select the Web Context tab.

    2. Enter bookstore2.

  • Deploy the app.

    1. Select ToolsDeploy.

    2. Click Finish.

  • Open the bookstore URL http://<host>:8000/bookstore2/enter.

 

The Life Cycle of a JSP Page

A JSP page services requests as a servlet. Thus, the life cycle and many of the capabilities of JSP pages (in particular the dynamic aspects) are determined by Java Servlet technology.

When a request is mapped to a JSP page, it is handled by a special servlet that first checks whether the JSP page's servlet is older than the JSP page. If it is, it translates the JSP page into a servlet class and compiles the class. During development, one of the advantages of JSP pages over servlets is that the build process is performed automatically.

 

Translation and Compilation

During the translation phase, each type of data in a JSP page is treated differently. Template data is transformed into code that will emit the data into the stream that returns data to the client. JSP elements are treated as follows:

  • Directives are used to control how the Web container translates and executes the JSP page.

  • Scripting elements are inserted into the JSP page's servlet class.

  • Elements of the form <jsp:XXX ... /> are converted into method calls to JavaBeans components or invocations of the Java Servlet API.

For a JSP page named pageName, the source for a JSP page's servlet is kept in the file

J2EE_HOME/repository/host/web/
   context_root/_0002fpageName_jsp.java

For example, the source for the index page named(index.jsp) for the date localization example discussed at the beginning of the chapter would be named

J2EE_HOME/repository/host/web/date/_0002findex_jsp.java

Both the translation and compilation phases can yield errors that are only observed when the page is requested for the first time. If an error occurs while the page is being translated (for example, if the translator encounters a malformed JSP element), the server will return a ParseException, and the servlet class source file will be empty or incomplete. The last incomplete line will give a pointer to the incorrect JSP element.

If an error occurs while the JSP page is being compiled (for example, there is a syntax error in a scriptlet), the server will return a JasperException and a message that includes the name of the JSP page's servlet and the line where the error occurred.

Once the page has been translated and compiled, the JSP page's servlet for the most part follows the servlet life cycle.

  1. If an instance of the JSP page's servlet does not exist, the container:

    1. Loads the JSP page's servlet class

    2. Instantiates an instance of the servlet class

    3. Initializes the servlet instance by calling the jspInit method

  2. Invokes the _jspService method, passing a request and response object.

If the container needs to remove the JSP page's servlet, it calls the jspDestroy method.

 

Execution

You can control various JSP page execution parameters using by page directives. The directives that pertain to buffering output and handling errors are discussed here. Other directives are covered in the context of specific page authoring tasks throughout the chapter.

Buffering

When a JSP page is executed, output written to the response object is automatically buffered. You can set the size of the buffer with the following page directive:

<%@ page buffer="none|xxxkb" %>

A larger buffer allows more content to be written before anything is actually sent back to the client, thus providing the JSP page with more time to set appropriate status codes and headers or to forward to another Web resource. A smaller buffer decreases server memory load and allows the client to start receiving data more quickly.

Handling Errors

Any number of exceptions can arise when a JSP page is executed. To specify that the Web container should forward control to an error page if an exception occurs, include the following page directive at the beginning of your JSP page:

<%@ page errorPage="file_name" %>

The Duke's Bookstore app page initdestroy.jsp contains the directive

<%@ page errorPage="errorpage.jsp"%>

The beginning of errorpage.jsp indicates that it is serving as an error page with the following page directive:

<%@ page isErrorPage="true|false" %>

This directive makes the exception object (of type javax.servlet.jsp.JspException) available to the error page, so that you can retrieve, interpret, and possibly display information about the cause of the exception in the error page.


Note: You can also define error pages for the WAR that contains a JSP page. If error pages are defined for both the WAR and a JSP page, the JSP page's error page takes precedence.

 

Initializing and Finalizing a JSP Page

You can customize the initialization process to allow the JSP page to read persistent configuration data, initialize resources, and perform any other one-time activities by overriding the jspInit method of the JspPage interface. You release resources using the jspDestroy method. The methods are defined using JSP declarations.

The bookstore example page initdestroy.jsp defines the jspInit method to retrieve or create an enterprise bean database.BookDBEJB that accesses the bookstore database; initdestroy.jsp stores a reference to the bean in bookDBEJB.

private BookDBEJB bookDBEJB;
public void jspInit() {
   bookDBEJB =
      (BookDB)getServletContext().getAttribute("bookDBEJB");
   if (bookDBEJB == null) {
      try {

         InitialContext ic = new InitialContext();
         Object objRef = ic.lookup(
            "java:comp/env/ejb/BookDBEJB");
         BookDBEJBHome home =
            (BookDBEJBHome)PortableRemoteObject.narrow(objRef,
               database.BookDBEJBHome.class);
         bookDBEJB = home.create();
         getServletContext().setAttribute("bookDBEJB",
            bookDBEJB);

      } catch (RemoteException ex) {
         System.out.println(
            "Couldn't create database bean." + ex.getMessage());
      } catch (CreateException ex) {
         System.out.println(
            "Couldn't create database bean." + ex.getMessage());
      } catch (NamingException ex) {
         System.out.println("Unable to lookup home: " +
            "java:comp/env/ejb/BookDBEJB."+ ex.getMessage());
      }
   }
}

When the JSP page is removed from service, the jspDestroy method releases the BookDBEJB variable:

public void jspDestroy() {
   bookDBEJB = null;
}

Since the enterprise bean is shared between all the JSP pages, it should be initialized when the app is started, instead of in each JSP page. Java Servlet technology provides app life cycle events and listener classes for this purpose. As an exercise, you can move the code that manages the creation of the enterprise bean to a context listener class.

 

Creating Static Content

You create static content in a JSP page by simply writing it as if you were creating a page that consisted only of that content. Static content can be expressed in any text-based format, such as HTML, WML, and XML. The default format is HTML. If you want to use a format other than HTML, you include a page directive with the contentType attribute set to the format type at the beginning of your JSP page. For example, if you want a page to contain data expressed in the wireless markup language (WML), you need to include the following directive:

<%@ page contentType="text/vnd.wap.wml"%>

A registry of content type names is kept by the IANA at

ftp://ftp.isi.edu/in-notes/iana/assignments/media-types

 

Creating Dynamic Content

You create dynamic content by accessing Java programming language objects from within scripting elements.

 

Using Objects within JSP Pages

You can access a variety of objects including enterprise beans and JavaBeans components, within a JSP page. JSP technology automatically makes some objects available, and you can also create and access app-specific objects.

Implicit Objects

Implicit objects are created by the Web container and contain information related to a particular request, page, or app.

 

Variable Class Description
app javax.servlet.ServletContext The context for the JSP page's servlet and any Web components contained in the same app.
config javax.servlet.ServletConfig Initialization information for the JSP page's servlet.
exception java.lang.Throwable Accessible only from an error page.
out javax.servlet.jsp.JspWriter The output stream.
page java.lang.Object The instance of the JSP page's servlet processing the current request. Not typically used by JSP page authors.
pageContext javax.servlet.jsp.PageContext The context for the JSP page. Provides a single API to manage the various scoped attributes described in Sharing Information.
This API is used extensively when implementing tag handlers.
request Subtype of javax.servlet.ServletRequest The request triggering the execution of the JSP page.
response Subtype of javax.servlet.ServletResponse The response to be returned to the client. Not typically used by JSP page authors.
session javax.servlet.http.HttpSession
The session object for the client.

Application-Specific Objects

When possible, app behavior should be encapsulated in objects so that page designers can focus on presentation issues. Objects can be created by developers who are proficient in the Java programming language and in accessing databases and other services. There are four ways to create and use objects within a JSP page:

  • Instance and class variables of the JSP page's servlet class are created in declarations and accessed in scriptlets and expressions.

  • Local variables of the JSP page's servlet class are created and used in scriptlets and expressions.

  • Attributes of scope objects are created and used in scriptlets and expressions.

  • JavaBeans components can be created and accessed using streamlined JSP elements. You can also create a JavaBeans component in a declaration or scriptlet and invoke the methods of a JavaBeans component in a scriptlet or expression.

Shared Objects

The conditions affecting concurrent access to shared objects described in Sharing Information apply to objects accessed from JSP pages that run as multithreaded servlets. You can indicate how a Web container should dispatch multiple client requests with the following page directive:

<%@ page isThreadSafe="true|false" %>

When isThreadSafe is set to true, the Web container may choose to dispatch multiple concurrent client requests to the JSP page. This is the default setting. If using true, ensure that you properly synchronize access to any shared objects defined at the page level. This includes objects created within declarations, JavaBeans components with page scope, and attributes of the page scope object.

If isThreadSafe is set to false, requests are dispatched one at a time, in the order they were received, and access to page-level objects does not have to be controlled. However, you still must ensure that access to attributes of the app or session scope objects and to JavaBeans components with app or session scope is properly synchronized.

 

JSP Scripting Elements

JSP scripting elements are used to create and access objects define methods, and manage the flow of control. Since one of the goals of JSP technology is to separate static template data from the code needed to dynamically generate content, very sparing use of JSP scripting is recommended. Much of the work that requires the use of scripts can be eliminated by using custom tags.

JSP technology allows a container to support any scripting language that can call Java objects. If you wish to use a scripting language other than the default, java, specify it in a page directive at the beginning of a JSP page:

<%@ page language="scripting language" %>

Since scripting elements are converted to programming language statements in the JSP page's servlet class, import any classes and packages used by a JSP page. If the page language is java, you import a class or package with the page directive:

<%@ page import="packagename.*, fully_qualified_classname" %>

For example, the bookstore example page showcart.jsp imports the classes needed to implement the shopping cart with the following directive:

<%@ page import="java.util.*, cart.*" %>

Declarations

A JSP declaration is used to declare variables and methods in a page's scripting language. The syntax for a declaration is as follows:

<%! scripting language declaration %>

When the scripting language is the Java programming language, variables and methods in JSP declarations become declarations in the JSP page's servlet class.

The bookstore example page initdestroy.jsp defines an instance variable named bookDBEJB and the initialization and finalization methods jspInit and jspDestroy discussed earlier in a declaration:

<%!
   private BookDBEJB bookDBEJB;

   public void jspInit() {
      ...
   }
   public void jspDestroy() {
      ...
   }
%>

Scriptlets

A JSP scriptlet is used to contain any code fragment that is valid for the scripting language used in a page. The syntax for a scriptlet is as follows:

<%
   scripting language statements
%>

When the scripting language is set to java, a scriptlet is transformed into a Java programming language statement fragment and is inserted into the service method of the JSP page's servlet. A programming language variable created within a scriptlet is accessible from anywhere within the JSP page.

The JSP page showcart.jsp contains a scriptlet that retrieves an iterator from the collection of items maintained by a shopping cart and sets up a construct to loop through all the items in the cart. Inside the loop, the JSP page extracts properties of the book objects and formats them using HTML markup. Since the while loop opens a block, the HTML markup is followed by a scriptlet that closes the block.

<% 
   Iterator i = cart.getItems().iterator();
   while (i.hasNext()) {
      ShoppingCartItem item =
         (ShoppingCartItem)i.next();
      BookDetails bd = (BookDetails)item.getItem();
%>

      <tr> 
      <td align="right"> 
      <%=item.getQuantity()%>
      </td> 
      <td> 
      <b><a href="
      <%=request.getContextPath()%>/bookdetails?bookId=
      <%=bd.getBookId()%>"><%=bd.getTitle()%></a></b> 
      </td> 
      ...
<%
   // End of while
   }
%>

Expressions

A JSP expression is used to insert the value of a scripting language expression, converted into a string, into the data stream returned to the client. When the scripting language is the Java programming language, an expression is transformed into a statement that converts the value of the expression into a String object and inserts it into the implicit out object.

The syntax for an expression is as follows:

<%= scripting language expression %>

Note that a semicolon is not allowed within a JSP expression, even if the same expression has a semicolon when you use it within a scriptlet.

The following scriptlet retrieves the number of items in a shopping cart:

<%
   // Print a summary of the shopping cart
   int num = cart.getNumberOfItems();
   if (num > 0) {
%>

Duke's Bookstore Shopping Cart

Expressions are then used to insert the value of num into the output stream and determine the appropriate string to include after the number:

<font size="+2">
<%=messages.getString("CartContents")%> <%=num%> 
   <%=(num==1 ? <%=messages.getString("CartItem")%> :
   <%=messages.getString("CartItems"))%></font>

 

Including Content in a JSP Page

There are two mechanisms for including another Web resource in a JSP page: the include directive and the jsp:include element.

The include directive is processed when the JSP page is translated into a servlet class. The effect of the directive is to insert the text contained in another file--either static content or another JSP page--in the including JSP page. You would probably use the include directive to include banner content, copyright information, or any chunk of content that you might want to reuse in another page. The syntax for the include directive is as follows:

<%@ include file="filename" %>

For example, all the bookstore app pages include the file banner.jsp containing the banner content with the following directive:

<%@ include file="banner.jsp" %>

In addition, the pages bookstore.jsp, bookdetails.jsp, catalog.jsp, and showcart.jsp include JSP elements that create and destroy a database bean with the following directive:

<%@ include file="initdestroy.jsp" %>

Because statically put an include directive in each file that reuses the resource referenced by the directive, this approach has its limitations.

The jsp:include element is processed when a JSP page is executed. The include action allows you to include either a static or dynamic resource in a JSP file. The results of including static and dynamic resources are quite different. If the resource is static, its content is inserted into the calling JSP file. If the resource is dynamic, the request is sent to the included resource, the included page is executed, and then the result is included in the response from the calling JSP page. The syntax for the jsp:include element is as follows:

<jsp:include page="includedPage" />

The date app introduced at the beginning of this chapter includes the page that generates the display of the localized date with the following statement:

<jsp:include page="date.jsp"/>

 

Transferring Control

<jsp:forward page="/main.jsp" />

Note that if any data has already been returned to a client, the jsp:forward element will fail with an IllegalStateException.

 

Param Element

When an include or forward element is invoked, the original request object is provided to the target page. If you wish to provide additional data to that page, you can append parameters to the request object with the jsp:param element:

<jsp:include page="..." >
   <jsp:param name="param1" value="value1"/>
</jsp:include>

 

Including an Applet

You can include an applet or JavaBeans component in a JSP page by using the jsp:plugin element. This element generates HTML that contains the appropriate client-browser-dependent constructs (<object> or <embed>) that will result in the download of the Java Plug-in software (if required) and client-side component and subsequent execution of any client-side component. The syntax for the jsp:plugin element is as follows:

<jsp:plugin 
   type="bean|applet" 
   code="objectCode" 
   codebase="objectCodebase" 
   { align="alignment" } 
   { archive="archiveList" } 
   { height="height" } 
   { hspace="hspace" } 
   { jreversion="jreversion" } 
   { name="componentName" } 
   { vspace="vspace" } 
   { width="width" } 
   { nspluginurl="url" } 
   { iepluginurl="url" } > 
   { <jsp:params> 
      { <jsp:param name="paramName" value="paramValue" /> }+
   </jsp:params> } 
   { <jsp:fallback> arbitrary_text </jsp:fallback> } 
</jsp:plugin>

The jsp:plugin tag is replaced by either an <object> or <embed> tag as appropriate for the requesting client. The attributes of the jsp:plugin tag provide configuration data for the presentation of the element as well as the version of the plug-in required. The nspluginurl and iepluginurl attributes specify the URL where the plug-in can be downloaded.

The jsp:param elements specify parameters to the applet or JavaBeans component. The jsp:fallback element indicates the content to be used by the client browser if the plug-in cannot be started (either because <object> or <embed> is not supported by the client or because of some other problem).

If the plug-in can start but the applet or JavaBeans component cannot be found or started, a plug-in-specific message will be presented to the user, most likely a pop-up window reporting a ClassNotFoundException.

The Duke's Bookstore page banner.jsp that creates the banner displays a dynamic digital clock generated by DigitalClock.

The jsp:plugin element used to download the applet follows:

<jsp:plugin 
   type="applet" 
   code="DigitalClock.class" 
   codebase="/bookstore2" 
   jreversion="1.3" 
   align="center"
   nspluginurl="http://java.sun.com/products/plugin/1.3.0_01
      /plugin-install.html" 
   iepluginurl="http://java.sun.com/products/plugin/1.3.0_01
      /jinstall-130_01-win32.cab#Version=1,3,0,1" >
   <jsp:params>
      <jsp:param name="language"
         value="<%=request.getLocale().getLanguage()%>" />
      <jsp:param name="country"
         value="<%=request.getLocale().getCountry()%>" />
      <jsp:param name="bgcolor" value="FFFFFF" />
      <jsp:param name="fgcolor" value="CC0066" />
   </jsp:params>
      <jsp:fallback>
      <p>Unable to start plugin.</p>
   </jsp:fallback>
</jsp:plugin>

 

Extending the JSP Language

You can perform a wide variety of dynamic processing tasks including accessing databases, using enterprise services such as e-mail and directories, and managing 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 level 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"> 
      <%=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"> 
   <%=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>; however, for custom tags, prefix is defined by the user of the tag library and tag is defined by the tag developer.