Home > Articles > Programming > Java

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020