Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

JavaServer Pages

JavaServer Pages (JSP) is an interesting, and sometimes controversial, strategy for developing Web presentations. Whether or not you are a fan of JSP, it is a de facto standard by virtue of its incorporation into the Java 2 Enterprise Edition (J2EE) specification, not to mention the very large audience of JSP developers that exist today. Over time, it has been extended from the simple embedding of Java statements within an HTML page to the latest version, which now includes support for custom tags, or taglibs.

The distinguishing attribute of JSP is flexibility. A developer has the option of inserting Java directly into HTML or leveraging taglibs to achieve better separation of markup and Java logic. For our purposes, we'll start with the standard examples of JSP, later evolving them to introduce the topic of custom tags.

The name "JavaServer Page" somewhat implies its role. Java is inserted into a markup page for the purpose of generating dynamic content. The result is a hybrid of HTML or another markup language such as XML or WML intermixed with JSP tags and/or markup comments incorporating contiguous and non-contiguous calls to the Java language.

JavaServer Pages are not processed until the first invocation of the Web application. The algorithm for serving a page from a JSP environment is thus:

  1. The request for a JSP, as generated from a client, comes from the Web server.

  2. If the request has been seen before, skip to Step 4. If the JSP has never been requested since the application server was booted, the JSP is translated into a Java servlet source file. This translation is also carried out by a reloading mechanism if the JSP has been re-introduced by the developer.

  3. The class is compiled into a Java class.

  4. The servlet class is then loaded into the Web/servlet container for execution.

  5. The servlet streams HTML back to the Web server and onto the client.

All the embedded Java code is turned into one big method in the generated servlet. The URL request from a client might look something like

http://localhost:9000/myDemoApp/showChildren.jsp?value="Claire"

The servlet runner has been configured to associate the URL with the specific JSP, handing the request over to the Web container. Assuming the requested JSP page has been used before, the JSP engine then locates and loads the Java class that matches the name showChildren.class. If it's the first time the page has been requested, the JSP engine generates the class from the runtime compilation of the JSP file.

Inside the Web container, an application servlet is loaded into execution. A call is made to the init() method in order to perform last-minute setup and housekeeping chores, such as loading configuration information, before the servlet begins to accept requests. Eventually, calls to jspInit() launch the JSP-generated servlets. And for each HTTP request thereafter, the servlet creates a new thread to run service(). For JSP servlets, jspService(), a direct product of JSP page compilation, is called by service().

JSP Expressions, Declarations and Scriptlets

JSP is most well known for its capability to embed Java code directly in the markup page. For example, the following code fragment demonstrates the use of the JSP <%= and %> tags to insert a JSP expression. The first statement is actually a JSP directive, explained later. A JSP expression returns a string value to a response stream:

<%@ page import="java.util.Date, java.text.DateFormat" %>
<html>
<body>
<P>Welcome to JSP development
where the time is: <%= DateFormat.getTimeInstance().format((new Date()) %>
</body>
</html>

In expressions, you'll note the absence of the statement-ending semicolon. This is a JSP-ism that is required only of expressions, not of declarations or scriptlets. The golden rule of JSP programming is that every JSP expression must return a string or a primitive. If any part of an expression returns an object, the toString() method is invoked.

Listing 3.2 illustrates the use of expressions, declarations, and scriptlets. A declaration is used to define an array of daughters and their ages. A scriptlet is then used to traverse the array of daughters, generating rows of cells with each daughter's name and age. The actual name and age is embedded in the cell with two JSP expressions.

Listing 3.2 Expression, Declaration, and Scriptlet Usage in a JSP Page

<%@ page contentType="text/html;charset=WINDOWS-1252"%>
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=WINDOWS-1252">
<META NAME="ENHYDRA" CONTENT="ToolBox">
<TITLE>
Server side redirect
</TITLE>
</HEAD>
<BODY>
<%! String daughters[][] = {{"Amanda","16"}, { "Claire","1"}, _{"Nicole","11"}}; %>
<h1>Dynamic demo using static data</h1>
<TABLE BORDER=1>
<%
for (int i=0; i<daughters.length;i++){
%>
    <TR><TD><%= daughters[i][0] %></TD>
    <TD><%= daughters[i][1] %></TD></TR>
<%
}
%>
</TABLE>
</BODY>
</HTML>

Note

Although modern HTML design tools can now work comfortably with hybrid pages of JSP and HTML, the issue of mocking up meaningful prototypes still requires the designer to build a parallel document for customer review. The designer must then ensure that the two documents are kept in sync. As discussed earlier, support for included mocked-up content is a distinguishing feature of XMLC.

JSP Directives

JSP directives, identified by their surrounding <%@ and %> tags, are instructions and information passed to the JSP engine during page translation and compilation. This is how JSP pages influence control over how the servlet is built. JSP directives take effect at the time that the JSP page is translated into a servlet. Therefore, once the servlet exists, the directive can no longer be changed without forcing the servlet to be rebuilt.

The page directive deals with such topics as error page re-direction, importing of Java classes, the setting of content type and the setting of the output stream buffering and the associated autoFlush flag. The following page directive indicates that the JSP will generate output for an SVG (Scalar Vector Graphic) viewer:

<%@ page contentType="text/svg-xml" %>

The include directive notifies the servlet container to perform an inline inclusion of another JSP page. This approach can be used to minimize the obvious Java presence in a page, thus reducing the potential for errors created by HTML designers:

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

File inclusion happens only when the JSP is translated into a servlet. In the example, if any changes are made afterwards to menuBar.jsp, no effect will be seen.

The taglib directive is best known to XMLC programmers, because they tend to hear the phrase "JSP taglibs are just like XMLC." This topic deserves the attention we give it later in the chapter.

JSP, Servlets, and JSP Implicit Objects

The topic of JSP implicit objects is an interesting one. These are Servlet API methods that are made available for use by scriptlets via wrappers. Each object is listed with its associated implementation class (in parentheses):

  • request (HTTPServletRequest)
  • response (HTTPServletResponse)
  • application (ServletContext)
  • config (ServletConfig)
  • page (Object)
  • out (JspWriter)
  • exception (Throwable)
  • pageContext (PageContext)
  • session (HttpSession)

These are described as JSP features, but all they really are access points to the underlying servlet container. There is nothing unique about JSP that makes the information they contain available only to the JSP environment.

JSP Taglibs

To say the least, standard JSP programming is a clear example of tight coupling between two very different languages and two very different development practices, namely HTML and Java. The good news is that over time, modern HTML design tools such as Macromedia's Dreamweaver and Adobe's GoLive, have learned to handle non-standard HTML tags. The result is that the design community can now interact more directly with Java developers.

Supporters of JSP maintain that JSP helps to maintain the healthy separation of HTML designer and Java roles. To make this claim, they are really relying on "best practices" to suggest a heavy reliance on encapsulating functionality inside Java Beans. Some would consider that claim to be a bit of "marketecture," but let's take a look at custom tags, the next great hope for true separation of content from logic.

Better encapsulation and separation of markup from programming logic is the goal of JSP's Custom Tag Libraries, referred to as taglibs. This capability has spawned many organized efforts including Apache Struts and, for better or worse, product-specific library definitions. Before we talk about the implications of this newest wrinkle in JSP development, let's review how it works.

Taglibs enable the indirect embedding of Java logic via the use of developer-defined HTML/XML tags. A custom tag may have a body or no body. Examples here leverage a possible tag library called "showFloor:"

<showFloor:displayBoothInfo customer="ACME"/>

or

<showFloor:displayBoothDescription>
This is a rectangular booth in the middle of the floor.
</showFloor:displayBoothDescription>

It's even permissible to use JSP expressions to complement custom tags:

<showFloor:login date="<%= today %>" />

Table 3.1 lists the types of tags and the methods as defined by the tag library interface that the developer must implement in order to process the tags. For example, if you are writing a tag that is going to process the content within the body of the tag, such as the preceding showFloor:displayBoothDescription tag, then you must implement doInitBody() and doAfterBody().

Table 3.1 Tag Handler Types and Their Required Methods

Tag Handler Type

Methods

Simple

doStartTag, doEndTag, release

Attributes

doStartTag, doEndTag, set/getAttribute1...N

Body, No Interaction

doStartTag, doEndTag, release

Body, Interaction

doStartTag, doEndTag, release, doInitBody, doAfterBody


Creating a Custom Tag

Creating a custom tag requires the creation of a Java-based tag handler that implements the tag. With a tag handler in hand, you must then associate the JSP with a tag library descriptor file, cross-referencing the tag library with the custom tag. Creating custom tags requires two significant steps:

  1. Create the tag handler.

  2. The tag handler is the actual core of your tag library. A tag handler will reference other entities, such as JavaBeans. It has full access to all the information from your page using the pageContext object. It is handed all the information associated with the custom tag, including attributes and body content. As processing completes, the tag handler sends the output back to your JSP page to process.

  3. Create the Tag Library Descriptor (TLD).

  4. This is a simple XML file that references the tag handler. The servlet container is told everything it needs to associate the custom tag with the tag handler file. The markup fragment that follows shows how the JSP indicates the location of the TLD file using a tag library declaration:

  5. <% taglib uri="WEB-INF/showfloor.tld" prefix="showfloor">

  6. This defines the namespace, showfloor, that is associated with the tag lib dictionary, showfloor.tld.

Keeping true to the JSP attribute of flexibility, custom tags can be used in any manner of organization. For example, they can implement control flow behavior, such as the jLib:for custom tag in the example in Listing 3.3. This listing is taken from the Apache Jakarta taglibs project.

Listing 3.3 Using Jakarta's Taglib for Iterating an Array

<html>
<body>
<%@taglib uri="http://jakarta.apache.org/taglibs/utility" prefix="jLib" %>
<%! String [] color = new String[5]; %>
<%! String [] values = { "yellow", "red", "green", "blue", "pink"}; %>
<jLib:for varName="i" iterations="5">
 <% color[i.intValue()] = values[i.intValue()]; %>
</jLib:for>
<ul>
<jLib:for varName="j" iterations="<%= color.length %>" begin="2" >
 <jLib:If predicate="<%= j.intValue()==3 %>">
  <li> <%= color[j.intValue()] %>
 </jLib:If>
</jLib:for>
</ul>
</body>
</html>

You might ask, "Why not just write a Javabean that accomplishes similar results?" The answer is that taglibs are a mapping of Java functionality to the HTML/XML markup language format. It supports the "bindings" necessary for Java to participate in the XML structure. This becomes necessary in the absence of a leveraged DOM model.

The apparent value of taglibs is its capability to support standard, reusable functionality, as long as the industry is able to identify those standards. Sun's Java Community Process is attempting to address that goal with a committee of leading application server vendor representatives participating in JSR #52, "Standard Tag Library for JavaServer Pages."

Back-Filling in the Evolution of the Web

The Web is littered with a great many examples of back-filling to compensate for the fact that the Web infrastructure was really best-suited for "newspaper-style" publishing abilities, not highly dynamic, multiple-tier application development, deployment, and management. For example, browsers are inherently stateless. That drove the introduction of cookies as between-URL tokens that could help the CGI script "remember" what occurred before.

JSP taglibs are a similar notion. JSP was reverse engineered with taglibs in order to support better separation of presentation and business logic. HTML as an XML language is another one. Instead of fixing the widely deployed HTML, XHTML is the safer road taken.

  • + Share This
  • 🔖 Save To Your Account