JavaServer Pages 2.0

From the Expression Language to the JSP 2.0 API, new features in J2EE 1.4 change how you create custom JavaServer Pages.


July 01, 2003
URL:http://www.drdobbs.com/jvm/javaserver-pages-20/184405384

Jul03: JavaServer Pages 2.0

Aaron is chairman of Mantis Development Corp. and teaches computer graphics and Internet/web application development at Boston College. He is also author of J2EE 1.4 Essentials (http://www.wiley.com/ compbooks/walsh/). Aaron can be contacted at [email protected].


JavaServer Pages Standard Tag Library


JavaServer Pages (JSPs) work hand-in-hand with Java servlets to form the backbone of many Java-based web applications. Together they comprise the bulk of the Java 2 Platform Enterprise Edition's (J2EE's) so-called "web tier" that is ultimately responsible for connecting clients to server-side application components. Servlets are Java classes that extend and enhance the web server, and can be thought of as industrial-strength alternatives to CGI scripts. Servlets are commonly used to generate dynamic content on the fly in response to client requests, and can also act as controllers that govern aspects of client interaction with server-side application components.

While servlets give you a programmatic solution for handling web clients and generating dynamic content in response to HTTP client requests, JSPs are text-based documents that provide a familiar tag-based markup approach to creating static and dynamic web content. JSPs are relatively easy to create and offer an attractive alternative to servlets for nonprogrammers. They are intended primarily for web-page authors who aren't necessarily comfortable writing Java programs.

As a document-oriented servlet extension mechanism, JSPs offer many of the same capabilities of servlets without requiring extensive programming experience. Page authors create JSPs by entering JSP code consisting of elements and template data (markup such as HTML, XML, WML, and so on) directly into text documents, a process similar to that involved in creating normal web pages. JSP template data is markup that establishes the overall structure or layout of the page, while JSP elements include directives, actions, and scripting elements that are used to create various forms of dynamic content for the page.

JSPs are typically packaged in web applications with other JSP files, tag files and libraries, tag-handler Java classes, scripts, images, and any other files that make up the application. Packaged applications are then deployed to either JSP/Servlet or J2EE containers, where their contents are executed in response to client requests. Although JSPs are deployed as text documents, they are ultimately compiled into servlets that execute when the JSP is requested at run time, effectively putting the power of servlets directly in the hands of page authors. The JSP container automatically compiles JSPs into servlets that handle a request/response, as in Figure 1. The JSP is translated into a servlet and compiled the first time the page is requested, although these steps are skipped for subsequent requests of the same page. This process is entirely transparent to page authors who don't need to know or care about the low-level interaction between JSPs and servlets.

JSP 2.0

JSP 2.0, a required part of J2EE 1.4, improves on the 1.2 release by introducing features such as:

In short, JSP 2.0 is a major step forward that should substantially change the way JSP page authors and developers work.

The JSP 2.0 API

JSPs and servlets are inseparable from the perspective of JSPs—JSPs simply can't exist without servlets, although the opposite isn't true (servlets don't require JSPs). This dependency of JSPs on servlets is reflected in the JSP 2.0 API, which consists of packages defined by the Servlet API. In addition to the javax.servlet and javax.servlet.http packages already familiar to servlet developers, the JSP API consists of the javax.servlet.jsp, javax.servlet.jsp.el, and javax.servlet.jsp.tagext packages shown in Table 1. The JSP API is used by container vendors to implement JSP/Servlet containers, and by servlet programmers to implement tag handlers for custom actions.

The Expression Language

JSP 2.0 Expression Language is an outgrowth of the expression language originally defined by the JavaServer Pages Standard Tag Library (JSTL) 1.0 spec (see the accompanying text box entitled "JavaServer Pages Standard Tag Library"). EL is an official part of the JSP 2.0 spec, which has added features beyond the language introduced by JSTL 1.0. To accommodate these changes, JSTL 1.1 has been developed as a maintenance release that uses JSP 2.0 EL.

Influenced by ECMAScript and XPath, EL simplifies JSP development by making it easy for you to access JavaBeans, scoped variables, context-initialization and request parameters, and similar objects without resorting to Java. To take advantage of the EL, you write EL code in your pages using the syntax ${EL expression}.

EL can be used in JSP template text and within attribute values for both standard and custom actions that accept expressions. Listing One illustrates how EL can be used in attribute values; for example, where web3Dlogo identifies a JavaBean used by the page to display an image logo. When the page this code appears in is executed, the EL code is evaluated on the server-side by the container, sending the HTML in Listing Two to the client.

With EL, you can craft scriptless JSPs that are free of embedded Java code, encouraging a clean boundary between the presentational aspects of a page and the program logic it uses (typically, in the form of JavaBeans components). The scriptless JSP page in Listing Three, for instance, uses the code shown in Listing Four to dynamically populate the Web3D Web media submission form <select> menu in Figure 2.

EL is used in combination with the JSTL <forEach> tag to iterate over the collection of media-category names provided by the MediaCategories JavaBean (Listing Five) to populate the form menu presented to end users. After executing on the server, Listing Four generates the HTML code in Listing Six that is returned to the client as part of the larger web page created by this JSP.

Prior to JSP 2.0 and EL, the scriptlet in Listing Seven was used to achieve the same result (the complete application is available electronically; see "Resource Center," page 5), which required the unfortunate commingling of Java code with JSP code.

Although writing scriptlets such as this isn't a problem for Java programmers, it can be difficult for page authors. With JSP 2.0, Java programmers can focus on implementing tag handlers and low-level application development, leaving page authors to craft scriptless pages using pure JSP code. Granted, EL isn't as easy to use as basic markup and will take time for less experienced page authors to master. However, EL is considerably less complex than Java and easy enough for experienced page authors to learn. In particular, page authors already comfortable with client-side scripting languages (such as JavaScript, JScript, VBScript, and so forth) will find EL a cinch by comparison.

Simple Tag Handlers

Custom actions let the JSP language be extended to support tags that aren't built into it. Thanks to the extensible nature of JSP technology, both Java developers and page authors can implement custom tags to simplify page creation. Starting with JSP 2.0, page authors can implement custom tags using JSP code in tag files, while Java developers can create Java classes that implement the streamlined SimpleTag interface in Table 2.

Although JSP 2.0 still supports the classic tag handlers, you'll find the simple tag-handling mechanism easier to use. This is especially true if you extend the related javax.servlet.jsp.tagext.SimpleTagSupport class that provides a default implementation of all methods defined by the SimpleTag interface, as illustrated by the Media tag handler class in Listing Eight. This Java class extends the SimpleTagSupport class to implement a simple tag handler for the custom Web3D Web media action, and only has to override the doTag() method to completely handle this tag. When custom media tags appear in a JSP page, as shown in Listing Nine(a), the container automatically invokes the corresponding doTag() method defined by the media simple tag handler in Listing Eight.

This custom tag is used in the seaside.jsp page in Listing Ten. The first line of this JSP defines a prefix for all tags found in the given tag-library descriptor (TLD). A TLD is an XML file that describes the tag library and each tag that it contains. In Listing Nine(b), the prefix "web3Dweb" provides a unique namespace for all tags described in the web3Dweb.tld tag-library descriptor, of which "media" is one. When the custom media tag shown in Listing Ten is processed, the HTML code in Listing Nine(c) is generated by the handler and returned by the server to the client, which, in turn, delivers the specified 3D world to end users (see Figure 3).

The true power behind this custom action lies in its flexibility. Any piece of media content provided by the Web3D Web media network, regardless of its format, can be woven into a JSP using this tag. Listing Nine(d), for example, displays the snapshot of the animated Flash movie in Figure 4. In this case, the HTML code generated by the tag handler is different than that of the previous example because the tag configuration specifies a different piece of media. Similarly, if the page author configures the media tag incorrectly (specifying, for instance, media that doesn't exist on the network) or if the network can't deliver the requested media for any reason, the tag handler generates HTML code presenting an error message to the client.

Conclusion

Sun's J2EE 1.4 SDK supports JSP 2.0, and is freely available through Sun's J2EE homepage (http://java.sun.com/j2ee/). If you just want to use JSP 2.0, however, try Apache's free Tomcat 5 JSP/Servlet container (http://jakarta.apache.org/tomcat/). Sun's SDK is actually based, in part, on Apache Tomcat. In either case, arm yourself with the JSP 2.0 spec and related API documentation, both available at http://java.sun.com/products/jsp/. Additionally, you may find the JSP sections of Sun's J2EE Tutorial Addendum helpful (http://java.sun.com/j2ee/1.4/docs/tutorial/).

Acknowledgments

The JSP 2.0 examples I present here are provided courtesy of the Web3DWeb digital media network. Accessible through the traditional Web at http://Web3DWeb.com/, the Web3DWeb is a massively scalable digital-media network for interactive digital cinema, multiplayer 3D games, streaming media, and other forms of rich digital content. Built using open Internet and web standards layered on J2EE 1.4, the web client interface is constructed using JSP and servlets, a few of which I present here as real-world examples of JSP 2.0 in action. The media submission form, for instance, provides end users and members with a mechanism for submitting content to the network. Figures 3 and 4, on the other hand, illustrate how custom tags are used to simplify the process of delivering rich media content for page authors. The complete code for these applications, along with instructions on how to deploy and test them using the Tomcat 5 JSP/Servlet container, are also available electronically.

DDJ

Listing One

<jsp:useBean id="web3Dlogo" scope="application" class="web3Dweb.Logo"/>
<img src    = "${web3Dlogo.URL}" 
     height = "${web3Dlogo.high}" 
     width  = "${web3Dlogo.wide}"/>

Back to Article

Listing Two

<img src="http://web3dweb.com/images/web3Dweb_banner_75dpi.png" 
     width="780" height="239" /> 

Back to Article

Listing Three

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@ page import="web3Dweb.MediaCategories" %>
<%@ page contentType="text/html; charset=ISO-8859-5" %>
<html>
 <head>
  <title>Web3D Web Media Submission Form : JSP SCRIPTLET VERSION</title>
  <meta name="Author" content="Milena Mejia, Dean Hantzis, 
                               Ian Lamont, Aaron Walsh">
  <meta name="Copyright" content="Web3DWeb.com"> 
  <meta name="License" content="http://Web3DWeb.com/license">
  <link href="style.css" rel="stylesheet" type="text/css">
  <script src="validate.js" language="JavaScript" 
          type="text/javascript"></script>
 </head>
 <body>
  <h1>.: Web3D Web :.</h1>
  <h2>.: Media Submission Form :.</h2>
  <form name="submitForm" onsubmit="return validateForm(this)"
        method="post"     action="confirmSubmission.jsp">
  <table width="340" cellpadding="5" cellspacing="0"
         border="0" align="center" summary="Submission form">
   <tbody>
    <tr><td colspan="3">
     <strong>Title:</strong>
      <img alt="Required Field" name="titleerror" 
           src="blank.gif" width="118" height="10" border="0"><br>
      <input name="title" type="text" size="55" 
             maxlength="255" value="">
     </td> </tr>
    <tr><td colspan="3">
     <br>
     <strong>Creator:</strong>
       <img alt="Required Field" name="creatorerror" 
            src="blank.gif" width="118" height="10" border="0"><br>
       <input name="creator" type="text" size="55" 
              maxlength="255" value="">
    </td></tr>
    <tr><td colspan="3">
     <br>
     <strong>URL:</strong>
     <img alt="Required Field" name="urlerror" 
          src="blank.gif" width="118" height="10" border="0"><br>
     <input type="text" size="55" maxlength="255" 
            name="url" value="http://">
    </td></tr>
    <tr><td colspan="3" height="5"> </td></tr> 
    <tr><td colspan="3" align="center">
      <strong>Category:</strong> 
       <select name="category">
         <option value="0" selected="selected">????</option>
            <jsp:useBean id="categories" scope="application" 
                         class="web3Dweb.MediaCategories"/>
            <c:forEach var="item" items="${categories.mediaCategories}">
              <option><c:out value="${item}" /></option>
            </c:forEach>
       </select>
     <img alt="Required Field" name="categoryerror" 
          src="blank.gif" width="118" height="10" border="0">
    </td></tr>
    <tr> <td colspan="3" height="5"> </td> </tr>
    <tr> <td colspan="3">
     <strong>Brief Description:</strong>
      <img alt="Required Field" name="summaryerror" 
           src="blank.gif" width="118" height="10" border="0"><br>
      <textarea name="summary" cols="42" rows="8"></textarea>
    </td> </tr>
    <tr> <td colspan="3" height="5"> </td> </tr>
    <tr> <td colspan="3" align="center">
    <input type="submit" name="submitform" value="Submit"> 
    </td> </tr>
   </tbody>
  </table>
 </form>
</body>
</html>

Back to Article

Listing Four

<select name="category">
 <option value="0" selected="selected">????</option> 
  <jsp:useBean id="categories" 
               scope="application" class="web3Dweb.MediaCategories"/>
  <c:forEach var="item" items="${categories.mediaCategories}">
    <option><c:out value="${item}" /></option>
  </c:forEach>
</select>

Back to Article

Listing Five

package web3Dweb;
import java.util.*;
/** 
 * Web3D Web Media Categories testing JavaBean. Note that in production media 
 * categories are actually pulled live from a database.
 * @author Aaron E. Walsh
 * Copyright 2003, Web3D Web. All Rights Reserved.
 * Use subject to license terms: http://web3Dweb.com/license
 */
public class MediaCategories {
   private ArrayList mediaCategories;
   public MediaCategories() {
      mediaCategories = new ArrayList();
      mediaCategories.add("Movies");  
      mediaCategories.add("Music");
      mediaCategories.add("Games");
      mediaCategories.add("Fun");
      mediaCategories.add("Shopping");
      mediaCategories.add("Sports");
      mediaCategories.add("Videos");     
      mediaCategories.add("Worlds");      
      Collections.sort(mediaCategories);
      mediaCategories.add("Misc."); 
   }
   public Collection getMediaCategories() {
      return mediaCategories;
   }
}

Back to Article

Listing Six

<select name="category">
 <option value="0" selected="selected">????</option>
 <option>Fun</option>
 <option>Games</option>
 <option>Movies</option>
 <option>Music</option>
 <option>Shopping</option>
 <option>Sports</option>
 <option>Videos</option>
 <option>Worlds</option>
 <option>Misc.</option>
</select>

Back to Article

Listing Seven

<select name="category">
 <option value="0" selected="selected">????</option>
 <jsp:useBean id="categories"
              scope="application" class="web3Dweb.MediaCategories"/>
 <% 
   Iterator i = categories.getMediaCategories().iterator();
   while (i.hasNext()) {
     String cat = (String)i.next();
 %>
   <option><%=cat%></option>
 <% 
    } 
 %>
</select>

Back to Article

Listing Eight

/**
 * Media.java. JSP 2.0 Simple Tag Handler for the Web3D Web "media" tag
 * @author Aaron E. Walsh
 * Copyright 2003, Web3D Web. All Rights Reserved.
 * Use subject to license terms: http://web3Dweb.com/license
 */
package web3Dweb;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;

/* Dymamically constructs the appropriate HTML tag(s) for the
 * media specified by the Web3D Web "media" tag
 */
public class Media extends SimpleTagSupport {
  private String name, category, width, height;
  // tag attribute setter methods
  public void setName(String name) {this.name=name;} 
  public void setCategory(String category) {this.category=category;} 
  public void setWidth(String width) {this.width=width;} 
  public void setHeight(String height) {this.height=height;} 
  // tag handler doTag() method
  public void doTag() throws JspException, IOException {
    MediaResolver mr = new MediaResolver(name, category); 
    getJspContext().getOut().write( 
     "<object" +
     " data=\"" + mr.getURL() + "\"" +
     " type=\"" + mr.getMimeType() + "\"" +
     " width=\"" + width + "\"" +
     " height=\"" + height + "\"" +
     ">" +
     mr.getParameters() +
     "</object>"
    );
  }
}

Back to Article

Listing Nine

(a)

<web3Dweb:media name="seaside" category="world" 
                width="800" height="600"/>

(b) 
<%@ taglib prefix="web3Dweb" uri="/WEB-INF/tlds/web3Dweb.tld" %>

(c)
<object data="http://web3dchat.com/seaside/wrl.wrl" type="model/vrml"
        width="800" height="600">
 <param name="src" value="http://web3dchat.com/seaside/wrl.wrl">
</object>

(d)
<web3Dweb:media name="valentine card" category="movie" 
                width="800" height="600"/>

Back to Article

Listing Ten

<%@ taglib prefix="web3Dweb" uri="/WEB-INF/tlds/web3Dweb.tld" %>
<html>
  <head>
    <title>Web3D Web : Web3DWeb.com</title>
    <link href="style.css" rel="stylesheet" type="text/css">
    <meta name="Author" content="Aaron E. Walsh">
    <meta name="Copyright" content="Web3DWeb.com"> 
    <meta name="License" content="http://Web3DWeb.com/license">
  </head>
  <body bgcolor="white">
   <h1 align="center">IMMERSIVE WORLDS @ web3Dweb.com</h1>
   <h2>Your immersive 3D experience begins in a rustic seaside cabin. 
   Open the red doors and walk down to the sea, jump into the wooden boat, 
   dive into the water, and touch floating portals to enter new worlds...</h2>
   <web3Dweb:media name="seaside" category="world" width="800" height="600"/>
  </body>
</html>

Back to Article

Jul03: JavaServer Pages 2.0

Figure 1: JSPs are a document-based extension of servlets.

Jul03: JavaServer Pages 2.0

Figure 2: The Web3D Web media submission form is created using a scriptless JSP 2.0 page in which EL and JSTL dynamically populate the Category pop-up menu from a JavaBean component.

Jul03: JavaServer Pages 2.0

Figure 3: The <object> HTML tag the web browser uses to display this interactive 3D world is generated on the fly using JSP 2.0. Image courtesy of Gerardo Quintieri (http://Web3DWeb.com/people/gq/).

Jul03: JavaServer Pages 2.0

Figure 4: Any piece of media available on the Web3D Web, regardless of format, can be delivered to end users by configuring the custom media tag accordingly. Image courtesy of Barbara Mikolajczak (http://Web3DWeb.com/people/bjm/).

Jul03: JavaServer Pages Standard Tag Library

JavaServer Pages Standard Tag Library

The JSP Standard Tag Library (JSTL) is a premade tag library standardized through the Java Community Process that consists of numerous custom tags commonly required by JSP authors. JSTL includes tags for conditionals and iterators (see Listings Three and Four), internationalization and formatting, XML document manipulation, internationalization and formatting based on locales, SQL, and more. JSTL 1.1 supports the same expression language as JSP 2.0, and also provides an API you can use to programmatically configure JSTL tags and create custom tags that are in line with JSTL conventions. Although JSTL isn't a required part of either JSP 2.0 or J2EE 1.4, it is highly recommended for anyone serious about JSP development and will likely be built into forthcoming JSP 2.0 containers. Apache Tomcat 5, for example, supports JSTL "out of the box," as I suspect most JSP 2.0 containers and J2EE 1.4 environments will when such products begin to ship later this year. For more details, see http://java.sun.com/products/jsp/jstl/.

—A.E.W.

Jul03: JavaServer Pages 2.0

Table 1: JSP API packages.

Jul03: JavaServer Pages 2.0

Table 2: javax.servlet.jsp.tagext.SimpleTag interface.

Terms of Service | Privacy Statement | Copyright © 2024 UBM Tech, All rights reserved.