Channels ▼
RSS

JVM Languages

JavaServer Pages 2.0

Source Code Accompanies This Article. Download It Now.


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 aaron@mantiscorp.com.


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:

  • Support for the Servlet 2.4 specification, which JSPs use for web semantics. At a minimum, JSP 2.0 and Servlet 2.4 require a compliant standalone container that runs Version 1.3 or later of the Java 2 Platform, Standard Edition (J2SE). They can also be used in any conforming J2EE 1.4 container, which, in turn, requires J2SE 1.4.

  • An Expression Language (EL) that page authors can use to access data from JSPs along with an API for invoking the EL. The EL paves the way for scriptless JSPs that are free of scriptlets and Java expressions, providing a clean separation of presentation and logic.

  • Syntax elements that enable custom actions to be defined using JSP, meaning custom tags can now be implemented using pure JSP code (a custom action is invoked by a custom tag in a JSP, the underlying implementation for which now can be provided by a tag file that contains reusable JSP code). The JSP code that implements such custom actions is stored in tag files that have the .tag file extension (displayCatalog.tag, for instance) to facilitate encapsulation and encourage reuse.

  • A simplified tag-invocation protocol that corresponds to a new type of tag extension called "Simple Tag Extension." This extension makes it easier for both page authors and Java developers to implement custom tags in either JSP code or Java. Page authors who don't know Java can implement new tags using JSP code in tag files, for example, while Java developers can create more complex tag-handler classes either by implementing the javax.servlet.jsp.tagext.SimpleTag interface or extending the related javax.servlet.jsp.tagext.SimpleTag- Support class that provides a default implementation of the SimpleTag interface.

  • Support for JSP fragments, which are reusable pieces of JSP code that can be passed to a tag handler and invoked as needed. Whereas simple attributes are evaluated by the JSP container, fragment attributes are evaluated by tag handlers at the time the tag is invoked. In other words, JSP fragments enable a portion of JSP code to be encapsulated into a Java object that may be passed around and evaluated any number of times.

  • Better XML integration, thanks to a revised XML syntax that solves many of the XML-related problems found in JSP 1.2.

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) 
<pre><%@ taglib prefix="web3Dweb" uri="/WEB-INF/tlds/web3Dweb.tld" %>

(c)
<pre><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)
<pre><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


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.