Read it Now!
Reprint Licensing

Java Server Pages

By Hans Bergsten

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introducing JavaServer Pages
The Java 2 Enterprise Edition ( J2EE) has taken the once-chaotic task of building an Internet presence and transformed it to the point where developers can use Java to efficiently create multitier, server-side applications. Today, the Java Enterprise APIs have expanded to encompass a number of areas: RMI and CORBA for remote object handling, JDBC for database interaction, JNDI for accessing naming and directory services, Enterprise JavaBeans for creating reusable business components, JMS ( Java Messaging Service) for message-oriented middleware, and JTA ( Java Transaction API) for performing atomic transactions. In addition, J2EE supports servlets , an extremely popular Java substitute for CGI scripts. The combination of these technologies allows programmers to create distributed business solutions for a variety of tasks.
In late 1999, Sun Microsystems added a new element to the collection of Enterprise Java tools: JavaServer Pages ( JSP). JavaServer Pages are built on top of Java servlets and are designed to increase the efficiency in which programmers, and even nonprogrammers, can create web content. This book is all about JavaServer Pages.
Put succinctly, JavaServer Pages is a technology for developing web pages that include dynamic content. Unlike a plain HTML page, which contains static content that always remains the same, a JSP page can change its content based on any number of variable items, including the identity of the user, the user's browser type, information provided by the user, and selections made by the user. As you'll see later in the book, functionality such as this can be used to create web applications like shopping carts and employee directories.
A JSP page contains standard markup language elements, such as HTML tags, just like a regular web page. However, a JSP page also contains special JSP elements that allow the server to insert dynamic content in the page. JSP elements can be used for a wide variety of purposes, such as retrieving information from a database or registering user preferences. When a user asks for a JSP page, the server executes the JSP elements, merges the results with the static parts of the page, and sends the dynamically composed page back to the browser, as illustrated in Figure 1.1.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What Is JavaServer Pages?
Put succinctly, JavaServer Pages is a technology for developing web pages that include dynamic content. Unlike a plain HTML page, which contains static content that always remains the same, a JSP page can change its content based on any number of variable items, including the identity of the user, the user's browser type, information provided by the user, and selections made by the user. As you'll see later in the book, functionality such as this can be used to create web applications like shopping carts and employee directories.
A JSP page contains standard markup language elements, such as HTML tags, just like a regular web page. However, a JSP page also contains special JSP elements that allow the server to insert dynamic content in the page. JSP elements can be used for a wide variety of purposes, such as retrieving information from a database or registering user preferences. When a user asks for a JSP page, the server executes the JSP elements, merges the results with the static parts of the page, and sends the dynamically composed page back to the browser, as illustrated in Figure 1.1.
Figure 1.1: Generating dynamic content with JSP elements
JSP defines a number of standard elements useful for any web application, such as accessing JavaBeans components, passing control between pages, and sharing information between requests, pages, and users. Programmers can also extend the JSP syntax by implementing application-specific elements that perform tasks such as accessing databases and Enterprise JavaBeans, sending email, and generating HTML to present application-specific data. The combination of standard elements and custom elements allows for the creation of powerful web applications.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Why Use JSP?
In the early days of the Web, the Common Gateway Interface (CGI) was the only tool for developing dynamic web content. However, CGI is not an efficient solution. For every request that comes in, the web server has to create a new operating system process, load an interpreter and a script, execute the script, and then tear it all down again. This is very taxing for the server and doesn't scale well when the amount of traffic increases.
Numerous CGI alternatives and enhancements, such as FastCGI, mod_ perl from Apache, NSAPI from Netscape, ISAPI from Microsoft, and Java Servlets from Sun Microsystems, have been created over the years. While these solutions offer better performance and scalability, all of these technologies suffer from a common problem: they generate web pages by embedding HTML directly in programming language code. This pushes the creation of dynamic web pages exclusively into the realm of programmers. JavaServer Pages, however, changes all that.
JSP tackles the problem from the other direction. Instead of embedding HTML in programming code, JSP lets you embed specialized code (sometimes called scripting code) into HTML pages. Java is the default scripting language of JSP, but the JSP specification allows for other languages as well, such as JavaScript, Perl, and VBScript. We will begin looking at all the JSP elements in detail later, but at this point let's introduce you to a simple JSP page:
<html>
  <body bgcolor="white">

  <% java.util.Date clock = new java.util.Date( ); %>
  <% if (clock.getHours( ) < 12) { %>
    <h1>Good morning!</h1>
  <% } else if (clock.getHours( ) < 18) { %>
    <h1>Good day!</h1>
  <% } else { %>
    <h1>Good evening!</h1>
  <% } %>
  Welcome to our site, open 24 hours a day.
  </body>
</html>
This page inserts a different message to the user based on the time of day: "Good morning!" if the local time is before 12:00 P.M., "Good day!" if between 12:00 P.M. and 6:00 P.M., and "Good evening!" if after 6:00 P.M. When a user asks for this page, the JSP-enabled web server executes all the highlighted Java code and creates a static page that is sent back to the user's browser. For example, if the current time is 8:53 P.M., the resulting page sent from the server to the browser looks like this:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What You Need to Get Started
Before we begin, let's quickly look at what you need to run the examples and develop your own applications. You really need only three things:
  • A PC or workstation with a connection to the Internet, so you can download the software you need
  • A Java 2-compatible Java Software Development Kit ( Java 2 SDK)
  • A JSP 1.1-enabled web server, such as Apache Tomcat from the Jakarta Project
The Apache Tomcat server is the reference implementation for JSP 1.1. All the examples in this book were tested on Tomcat. In Chapter 4, I'll show you how to download, install, and configure the Tomcat server, as well as all the examples from this book.
In addition, there are a wide variety of other tools and servers that support JSP, from both open source projects and commercial companies. Close to 30 different server products support JSP to date, and roughly 10 authoring tools with varying degrees of JSP support are listed on Sun's JSP web site (http://java.sun.com/products/jsp/ ). Appendix E, also contains a collection of references to JSP-related products, web hosting services, and sites where you can learn more about JSP and related technologies. You may want to evaluate some of these products when you're ready to start developing your application, but all you really need to work with the examples in this book are a regular text editor, such as Notepad, vi, or Emacs, and of course the Tomcat server.
So let's get going and take a closer look at what JSP has to offer. We need a solid ground to stand on, though, so in the next chapter we will start with the foundations upon which JSP is built: HTTP and Java servlets.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: HTTP and Servlet Basics
Let's start this chapter by defining the term web application . We've all seen regular client-side applications. But what exactly is a web application? Loosely, we could define it as an application running on a server that a user accesses through a thin, general-purpose client. Today, the most common client is a web browser on a PC or workstation, but soon all kinds of clients will be used, such as wireless PDAs, cellular phones, and other specialized devices.
The lofty goal here is to access all the information and services you need from any type of device you happen to have in front of you. This means that the same simple client program must be able to talk to many different server applications, and the applications must be able to work with many different types of clients. To satisfy this need, the protocol of how a client and a server talk to each other must be defined in detail. That's exactly what the HyperText Transport Protocol (HTTP) is for.
The communication model defined by HTTP forms the foundation for all web application design. You therefore need a basic understanding of HTTP to develop applications that fit within the constraints of the protocol, no matter which server-side technology you use. In this chapter, we look at the most important details of HTTP that you need to be aware of as a web application developer.
One other item. This book is about using JSP as the server-side technology, so that's what we'll primarily focus on. As we saw in Chapter 1, JSP is based on the Java servlet technology. Both technologies share a lot of terminology and concepts, so knowing a bit about servlets will help you even when you develop pure JSP applications. And to really understand and use the full power of JSP, you need to know a fair bit about servlets. We will therefore take a quick look at servlet fundamentals in the last section of this chapter, including a programmer's introduction for those of you familiar with Java.
HTTP and all extended protocols based on HTTP are based on a very simple but powerful communications model. Here's how it works: a client, typically a web browser, sends a
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The HTTP Request/Response Model
HTTP and all extended protocols based on HTTP are based on a very simple but powerful communications model. Here's how it works: a client, typically a web browser, sends a request for a resource to a server, and the server sends back a response corresponding to the requested resource (or a response with an error message if it can't deliver the resource for some reason). A resource can be a simple HTML file, or it can be a program that stores the information sent in a database and generates a dynamic response. This request/response model is illustrated in Figure 2.1.
Figure 2.1: HTTP request/response with two resources
This simple model implies three things you need to be aware of:
  1. HTTP is a stateless protocol. This means that the server does not keep any information about the client after it sends its response, and therefore cannot recognize that multiple requests from the same client may be related.
  2. Web applications cannot easily provide the kind of immediate feedback typically found in standalone GUI applications such as word processors or traditional client-server applications. Every interaction between the client and the server requires a request/response exchange. Performing a request/response exchange when a user selects an item in a list box or fills out a form element is usually too taxing on the bandwidth available to most Internet users.
  3. There's nothing in the protocol that tells the server how a request is made; consequently, the server cannot distinguish between various methods of triggering the request on the client. For example, the HTTP protocol does not allow a web server to differentiate between an explicit request caused by clicking a link or submitting a form and an implicit request caused by resizing the browser window or using the browser's Back button. In addition, HTTP does not allow the server to invoke client-specific functions, such as going back in the browser history list or sending the response to a certain frame.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Servlets
The JSP specification is based on the Java servlet specification. In fact, JSP pages are often combined with servlets in the same application. So to use JSP effectively, it's important to understand the similarities and the concepts that apply to both technologies. In this section, we first take a brief look at what a servlet is, and then discuss the concepts shared by servlets and JSP pages. In Chapter 3, we'll take a closer look at how JSP pages are actually turned into servlets automatically.
If you're already familiar with servlets, this is old news. You can safely skip the rest of this chapter. If you're not familiar with programming, don't worry about the details. The important thing is that you get familiar with the concepts described in the remainder of this chapter.
In simple terms, a servlet is a piece of code that adds new functionality to a server (typically a web server), just like CGI and proprietary server extensions such as NSAPI and ISAPI. But compared to other technologies, servlets have a number of advantages:
Platform and vendor independence
Servlets are supported by all the major web servers and application servers, so a servlet-based solution doesn't tie you to one specific vendor. And because servlets are written in the Java programming language, they can be used on any operating system with a Java runtime environment.
Integration
Servlets are developed in Java and can therefore take advantage of all the other Java technologies, such as JDBC for database access, JNDI for directory access, RMI for remote resource access, etc. Starting with Version 2.2, the servlet specification is part of the Java 2 Enterprise Edition ( J2EE), making servlets an important ingredient of any large-scale enterprise application, with formalized relationships to other server-side technologies such as Enterprise JavaBeans (EJB).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Packaging Java Web Applications
A complete web application may consist of several different resources: JSP pages, servlets, applets, static HTML pages, custom tag libraries and other Java class files. Until very recently, different servers required an application with all these components to be installed and configured in different ways, making it very hard for web application developers to provide easy-to-use installation instructions and tools.
Version 2.2 of the servlet specification defines a portable way to package all these resources together, along with a deployment descriptor. A deployment descriptor is a file that outlines security requirements and describes how all the resources fit together. All files for the web application are placed in an archive file, called a Web Archive (WAR) file. A WAR file has a .war file extension and can be created with the Java jar command or a ZIP utility program such as WinZip (the same compression scheme is used).
All Servlet 2.2-compliant servers can install a WAR file and associate the application with a servlet context. During installation, a server is free to unpack the contents of the file and store it for runtime use in any way it sees fit, but the application developer needs to deal with only one delivery format. This standardized deployment format also enables server vendors to develop installation and configuration tools that make it easy to install a new web application.
The internal structure for a WAR file is defined by the JSP specification. During development, however, it's often more convenient to work with the web application files in an open filesystem instead of packaging and repackaging them into a WAR file every time you make a change. As a result, most containers support the WAR structure in an open filesystem as well.
The structure required for both is outlined here:
/index.html
/company/contact.html
/products/list.jsp
/images/banner.gif
/WEB-INF/web.xml
/WEB-INF/lib/bean.jar
/WEB-INF/lib/actions.jar
/WEB-INF/classes/com/mycorp/servlets/PurchaseServlet.class
/WEB-INF/classes/com/mycorp/util/MyUtils.class
/WEB-INF/...
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: JSP Overview
JSP is the latest Java technology for web application development, and is based on the servlet technology introduced in the previous chapter. While servlets are great in many ways, they are generally reserved for programmers. In this chapter, we look at the problems that JSP technology solves, the anatomy of a JSP page, the relationship between servlets and JSP, and how a JSP page is processed by the server.
In any web application, a program on the server processes requests and generates responses. In a simple one-page application, such as an online bulletin board, you don't need to be overly concerned about the design of this piece of code; all logic can be lumped together in a single program. But when the application grows into something bigger (spanning multiple pages, with more options and support for more types of clients) it's a different story. The way your site is designed is critical to how well it can be adapted to new requirements and continue to evolve. The good news is that JSP technology can be used in all kinds of web applications, from the simplest to the most complex. Therefore, this chapter also introduces the primary concepts in the design model recommended for web applications, and the different roles played by JSP and other Java technologies in this model.
In many Java servlet-based applications, processing the request and generating the response are both handled by a single servlet class. A example servlet looks like this:
public class OrderServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, 
        HttpServletResponse response)
        throws ServletException, IOException  {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter( );
        
        if (isOrderInfoValid(request)) {
            saveOrderInfo(request);
            out.println("<html>");
            out.println("  <head>");
            out.println("    <title>Order Confirmation</title>");
            out.println("  </head>");
            out.println("  <body>");
            out.println("    <h1>Order Confirmation</h1>");
            renderOrderInfo(request);
            out.println("  </body>");
            out.println("</html>");
       }
 ...
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Problem with Servlets
In many Java servlet-based applications, processing the request and generating the response are both handled by a single servlet class. A example servlet looks like this:
public class OrderServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, 
        HttpServletResponse response)
        throws ServletException, IOException  {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter( );
        
        if (isOrderInfoValid(request)) {
            saveOrderInfo(request);
            out.println("<html>");
            out.println("  <head>");
            out.println("    <title>Order Confirmation</title>");
            out.println("  </head>");
            out.println("  <body>");
            out.println("    <h1>Order Confirmation</h1>");
            renderOrderInfo(request);
            out.println("  </body>");
            out.println("</html>");
       }
 ...
If you're not a programmer, don't worry about all the details in this code. The point is that the servlet contains request processing and business logic (implemented by methods such as isOrderInfoValid( ) and saveOrderInfo( )) and also generates the response HTML code, embedded directly in the servlet code using println( ) calls. A more structured servlet application isolates different pieces of the processing in various reusable utility classes, and may also use a separate class library for generating the actual HTML elements in the response. But even so, the pure servlet-based approach still has a few problems:
  • Detailed Java programming knowledge is needed to develop and maintain all aspects of the application, since the processing code and the HTML elements are lumped together.
  • Changing the look and feel of the application, or adding support for a new type of client (such as a WML client), requires the servlet code to be updated and recompiled.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Anatomy of a JSP Page
A JSP page is simply a regular web page with JSP elements for generating the parts of the page that differ for each request, as shown in Figure 3.2.
Everything in the page that is not a JSP element is called template text . Template text can really be any text: HTML, WML, XML, or even plain text. Since HTML is by far the most common web page language in use today, most of the descriptions and examples in this book are HTML-based, but keep in mind that JSP has no dependency on HTML; it can be used with any markup language. Template text is always passed straight through to the browser.
Figure 3.2: Template text and JSP elements
When a JSP page request is processed, the template text and the dynamic content generated by the JSP elements are merged, and the result is sent as the response to the browser.
There are three types of elements with JavaServer Pages: directive, action, and scripting elements.
The directive elements, shown in Table 3.1, are used to specify information about the page itself that remains the same between page requests, for example, the scripting language used in the page, whether session tracking is required, and the name of a page that should be used to report errors, if any.
Table 3.1: Directive Elements
Element
Description
<%@ page ... %>
Defines page-dependent attributes, such as scripting language, error page, and buffering requirements
<%@ include ... %>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
JSP Processing
A JSP page cannot be sent as-is to the browser; all JSP elements must first be processed by the server. This is done by turning the JSP page into a servlet, and then executing the servlet.
Just as a web server needs a servlet container to provide an interface to servlets, the server needs a JSP container to process JSP pages. The JSP container is often implemented as a servlet configured to handle all requests for JSP pages. In fact, these two containers—a servlet container and a JSP container—are often combined into one package under the name web container (as it is referred to in the J2EE documentation).
A JSP container is responsible for converting the JSP page into a servlet (known as the JSP page implementation class ) and compiling the servlet. These two steps form the translation phase . The JSP container automatically initiates the translation phase for a page when the first request for the page is received. The translation phase takes a bit of time, of course, so a user notices a slight delay the first time a JSP page is requested. The translation phase can also be initiated explicitly; this is referred to as precompilation of a JSP page. Precompiling a JSP page avoids hitting the user with this delay, and is discussed in more detail in Chapter 12.
The JSP container is also responsible for invoking the JSP page implementation class to process each request and generate the response. This is called the request processing phase. The two phases are illustrated in Figure 3.3.
Figure 3.3: JSP page translation and processing phases
As long as the JSP page remains unchanged, any subsequent processing goes straight to the request processing phase (i.e., it simply executes the class file). When the JSP page is modified, it goes through the translation phase again before entering the request processing phase.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
JSP Application Design with MVC
JSP technology can play a part in everything from the simplest web application, such as an online phone list or an employee vacation planner, to full-fledged enterprise applications, such as a human resource application or a sophisticated online shopping site. How large a part JSP plays differs in each case, of course. In this section, we introduce a design model suitable for both simple and complex applications called Model-View-Controller (MVC).
MVC was first described by Xerox in a number of papers published in the late 1980s. The key point of using MVC is to separate components into three distinct units: the Model, the View, and the Controller. In a server application, we commonly classify the parts of the application as: business logic, presentation, and request processing. Business logic is the term used for the manipulation of an application's data, i.e., customer, product, and order information. Presentation refers to how the application is displayed to the user, i.e., the position, font, and size. And finally, request processing is what ties the business logic and presentation parts together. In MVC terms, the Model corresponds to business logic and data, the View to the presentation logic, and the Controller to the request processing.
Why use this design with JSP? The answer lies primarily in the first two elements. Remember that an application data structure and logic (the Model) is typically the most stable part of an application, while the presentation of that data (the View) changes fairly often. Just look at all the face-lifts that web sites have gone through to keep up with the latest fashion in web design. Yet, the data they present remains the same. Another common example of why presentation should be separated from the business logic is that you may want to present the data in different languages or present different subsets of the data to internal and external users. Access to the data through new types of devices, such as cell phones and Personal Digital Assistants (PDAs), is the latest trend. Each client type requires its own presentation format. It should come as no surprise, then, that separating business logic from presentation makes it easier to evolve an application as the requirements change; new presentation interfaces can be developed without touching the business logic.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Setting Up the JSP Environment
This book contains plenty of examples to illustrate all the JSP features. All examples were developed and tested with the JSP reference implementation, known as the Apache Tomcat server, which is developed by the Apache Jakarta project. In this chapter you will learn how to install the Tomcat server and add a web application containing all the examples used in this book. You can, of course, use any web server that supports JSP 1.1, but Tomcat is a good server for development and test purposes. You can learn more about the Jakarta project and Tomcat, as well as how you can participate in the development, at the Jakarta web site: http://jakarta.apache.org.
Tomcat is a pure Java web server with support for the Servlet 2.2 and JSP 1.1 specifications. To use it, you must first install a Java runtime environment. If you don't already have one, you can download a Java SDK for Windows, Linux, and Solaris at http://java.sun.com/j2se/.
I recommend that you install the Java 2 SDK as opposed to the slimmed-down Runtime Environment ( JRE) distribution. The reason is that JSP requires a Java compiler, which is included in the SDK but not in the JRE. Sun Microsystems has made the javac compiler from the SDK available separately for redistribution by the Apache Software Foundation. So technically, you could use the JRE and download the Java compiler as part of the Tomcat package, but even as I write this chapter, the exact legal conditions for distributing the compiler are changing.
Another alternative is to use the Jikes compiler from IBM (http://www10.software.ibm.com/developerworks/opensource/jikes/ ). Tomcat can be configured to use Jikes instead of the javac compiler from Sun; read the Tomcat documentation if you would like to try this. To make things simple, though, I suggest installing the Java 2 SDK from Sun. The examples were developed and tested with Java 2 SDK, Standard Edition, v1.2.2 and v1.3. I recommend that you use the latest version of the SDK available for your platform.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installing the Java Software Development Kit
Tomcat is a pure Java web server with support for the Servlet 2.2 and JSP 1.1 specifications. To use it, you must first install a Java runtime environment. If you don't already have one, you can download a Java SDK for Windows, Linux, and Solaris at http://java.sun.com/j2se/.
I recommend that you install the Java 2 SDK as opposed to the slimmed-down Runtime Environment ( JRE) distribution. The reason is that JSP requires a Java compiler, which is included in the SDK but not in the JRE. Sun Microsystems has made the javac compiler from the SDK available separately for redistribution by the Apache Software Foundation. So technically, you could use the JRE and download the Java compiler as part of the Tomcat package, but even as I write this chapter, the exact legal conditions for distributing the compiler are changing.
Another alternative is to use the Jikes compiler from IBM (http://www10.software.ibm.com/developerworks/opensource/jikes/ ). Tomcat can be configured to use Jikes instead of the javac compiler from Sun; read the Tomcat documentation if you would like to try this. To make things simple, though, I suggest installing the Java 2 SDK from Sun. The examples were developed and tested with Java 2 SDK, Standard Edition, v1.2.2 and v1.3. I recommend that you use the latest version of the SDK available for your platform.
If you need an SDK for a platform other than Windows, Linux, or Solaris, there's a partial list of ports made by other companies at Sun's web site:
http://java.sun.com/cgi-bin/java-ports.cgi/
Also check your operating system vendor's web site. Most operating system vendors have their own SDK implementation available for free.
Installation of the SDK varies depending on platform but is typically easy to do. Just follow the instructions on the web site where you download the SDK.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installing the Tomcat Server
You can download the Tomcat Server either in binary format or as source code that you compile yourself. If you're primarily interested in learning about JSP, I recommend that you use the binary download to run the examples in this book and develop your own applications. If you're a Java programmer and interested in seeing how Tomcat is implemented, feel free to download the source and take a look at the internals.
The binary distribution is available at:
http://jakarta.apache.org/downloads/binindex.html
On this page you find three types of builds:
  • Release builds
  • Milestone builds
  • Nightly builds
Release builds are stable releases that have been tested extensively and verified to comply with the servlet and JSP specifications. Milestone builds are created as intermediary steps towards a release build. They often contain new features that are not yet fully tested, but are generally known to work. A nightly build, however, may be very unstable. It's actually a snapshot of the latest source code and may have been tested only by the person who made the latest change. You should use a nightly build only if you're involved in the development of Tomcat.
You should download the latest release build. All examples in this book were developed and tested using the 3.2 (Beta 3) version, but any release later than 3.2 should work fine as well. When you click on the link for the latest release build and select the bin directory, you see a list of archive files in different formats, similar to Figure 4.1.
Figure 4.1: Release build packages
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Testing Tomcat
To test the server—assuming you're running Tomcat on the same machine as the browser and that you're using the default port for Tomcat (8080)—open a browser and enter the following URL in the Location/Address field:
http://localhost:8080/
The Tomcat main page is shown in the browser (see Figure 4.2), and you can now run all servlet and JSP examples bundled with Tomcat to make sure everything works.
Figure 4.2: The Tomcat main page
When you're done testing Tomcat, stop the server like this:
C:\Jakarta\jakarta-tomcat\bin> shutdown
            
You should always stop the server this way, as opposed to killing the Command Prompt window the server is running in. Otherwise, the applications don't get a chance to close down gracefully, and when you start to connect external resources, like a database, various problems may occur.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installing the Book Examples
All JSP pages, HTML pages, Java source code, and class files for the book examples can be downloaded directly from the O'Reilly web site:
http://www.oreilly.com/catalog/jserverpages/
They can also be downloaded from the book web site:
http://www.TheJSPBook.com
The file that contains all the examples is called jspbook.zip. Save the file on your hard drive, for instance in C:\JSPBook on a Windows platform, and unpack it:
C:\JSPBook> jar xvf jspbook.zip
            
You can use the same command on a Unix platform.
Two new directories are created: ora and src. The first directory contains all examples described in this book, and the second contains the Java source files for the JavaBeans, custom actions, and utility classes used in the examples.
The examples' directory structure complies to the standard Java web application format described in Chapter 2. You can therefore configure any Servlet 2.2-compliant web container to run the examples. If you like to use a container other than Tomcat, be sure to read the documentation for that container.
To install the example application for Tomcat, copy the web application directory structure to Tomcat's default directory for applications, called webapps. Use this command on a Windows platform:
C:\JSPBook> xcopy /s /i ora %TOMCAT_HOME%\webapps\ora
            
On a Unix platform it looks like this:
[hans@gefion /usr/local/jspbook] cp -R ora $TOMCAT_HOME/webapps
            
Recall from Chapter 2 that each web application in a server is associated with a unique URI prefix. When you install an application in Tomcat's webapps directory, the subdirectory name is automatically assigned as the URI prefix for the application ( /ora in this case).
At this point, you must shut down and restart the Tomcat server. After that, you can point your browser to the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Example Web Application Overview
The examples for this book are packaged as a standard Java web application, as described in Chapter 2. This file structure is supported by all Servlet 2.2-compliant servers, so you can use the example application as a guide when you create your own web applications. How a web application is installed is not defined by the specification, however, so it varies between servers. With Tomcat, you simply copy the file structure to the special webapps directory and restart the server. To modify the configuration information for an application, you need to edit the application's WEB-INF/web.xml file using a text editor. Other servers may offer special deployment tools that copy the files to where they belong and let you configure the application using a special tool, such as web-based forms.
If you look in the ora web application directory, you'll see that it contains an index.htm l file and a number of directories corresponding to chapters in this book. These directories contain all the example JSP and HTML pages.
There's also a WEB-INF directory with a web.xml file, a lib directory, a classes directory, and a tlds directory:
  • The web.xml file contains configuration information for the example application in the format defined by the Servlet 2.2 specification. It's too early to look at the contents of this file now; we will return to parts of it when needed.
  • The lib and classes directories are standard directories, also defined by the Servlet 2.2 specification. A common question asked by people new to servlets and JSP (prior to the standard web application format) was, "Where do I store my class files so that the server can find them?" The answer, unfortunately, differed depending on which implementation was used. With the standard web application format, however, it's easy to answer this question: if the classes are packaged in a JAR file, store the JAR file in the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Generating Dynamic Content
JSP is all about generating dynamic content: content that differs based on user input, time of day, the state of an external system, or any other runtime conditions. JSP provides you with lots of tools for generating this content. In this book, you will learn about all of them—standard actions, custom actions, JavaBeans, and scripting elements. Before we do that, however, let's start with a few simple examples to get a feel for how the basic JSP elements work.
In this chapter, we develop a page for displaying the current date and time, and look at the JSP directive element and how to use JavaBeans in a JSP page along the way. Next, we look at how to process user input in your JSP pages and make sure it has the appropriate format. We also look at how you can convert special characters in the output, so they don't confuse the browser.
Recall from Chapter 3, that a JSP page is just a regular HTML page with a few special elements. JSP pages should have the file extension .jsp , which tells the server that the page needs to be processed by the JSP container. Without this clue, the server is unable to distinguish a JSP page from any other type of file and sends it unprocessed to the browser.
When working with JSP pages, you really just need a regular text editor such as Notepad on Windows or Emacs on Unix. Appendix E, however, lists a number of tools that may make it easier for you, such as syntax-aware editors that color-code JSP and HTML elements. Some Interactive Development Environments (IDEs) include a small web container that allows you to easily execute and debug the page during development. There are also several web page authoring tools—the type of tools often used when developing regular HTML pages—that support JSP. I don't recommend that you use them initially; it's easier to learn how JSP works if you see the raw page elements before you use tools that hide them.
The first example JSP page, named date.jsp , is shown in Example 5.1.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What Time Is It?
Recall from Chapter 3, that a JSP page is just a regular HTML page with a few special elements. JSP pages should have the file extension .jsp , which tells the server that the page needs to be processed by the JSP container. Without this clue, the server is unable to distinguish a JSP page from any other type of file and sends it unprocessed to the browser.
When working with JSP pages, you really just need a regular text editor such as Notepad on Windows or Emacs on Unix. Appendix E, however, lists a number of tools that may make it easier for you, such as syntax-aware editors that color-code JSP and HTML elements. Some Interactive Development Environments (IDEs) include a small web container that allows you to easily execute and debug the page during development. There are also several web page authoring tools—the type of tools often used when developing regular HTML pages—that support JSP. I don't recommend that you use them initially; it's easier to learn how JSP works if you see the raw page elements before you use tools that hide them.
The first example JSP page, named date.jsp , is shown in Example 5.1.
Example 5.1. JSP Page Showing the Current Date and Time (date.jsp)
                  <%@ page language="java" contentType="text/html" %>
<html>
  <body bgcolor="white">

    <jsp:useBean id="clock" class="java.util.Date" />

    The current time at the server is:
    <ul>
      <li>Date: <jsp:getProperty name="clock" property="date" />
      <li>Month: <jsp:getProperty name="clock" property="month" />
      <li>Year: <jsp:getProperty name="clock" property="year" />
      <li>Hours: <jsp:getProperty name="clock" property="hours" />
      <li>Minutes: <jsp:getProperty name="clock" property="minutes" />
    </ul>

  </body>
</html>
The date.jsp page displays the current date and time. We'll look at all the different pieces soon, but first let's run the example to see how it works. Assuming you have installed all book examples as described in Chapter 4, first start the Tomcat server and load the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Input and Output
User input is a necessity in modern web pages. Most dynamic web sites generate pages based on user input. Unfortunately, users seldom enter information in exactly the format you need, so before you can use such input, you probably want to validate it.
And it's not only the input format that's important. Web browsers are also picky about the format of the HTML you send them. For instance, when you generate an HTML form with values taken from a database, a name such as O'Reilly can cause problems. The single quote character after the O can fool the browser into believing that it's at the end of the string, so you end up with just an O in your form.
As we saw earlier, a bean is often used as a container for data, created by some server process, and used in a JSP page that displays the data. But a bean can also be used to capture user input. The captured data can then be processed by the bean itself or used as input to some other server component (e.g., a component that stores the data in a database or picks an appropriate banner ad to display). The nice thing about using a bean this way is that all information is in one bundle. Say you have a bean that can contain information about a person, and it captures the name, birth date, and email address as entered by the person on a web form. You can then pass this bean to another component, providing all the information about the user in one shot. Now, if you want to add more information about the user, you just add properties to the bean, instead of having to add parameters all over the place in your code. Another benefit of using a bean to capture user input is that the bean can encapsulate all the rules about its properties. Thus, a bean representing a person can make sure the birthDate property is set to a valid date.
Using a bean to capture and validate user input is one aspect of building a web application that's easy to maintain and extend as requirements change. But it's not the only option. If you're a page author and intend to use JSP to develop sites using components from third parties, you may wonder how you can capture and validate input without access to a Java programmer who can develop the beans. Don't worry; we'll see another alternative in Chapter 9.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 6: Using Scripting Elements
When you develop a JSP-based application, I recommend that you try to place all Java code in JavaBeans, in custom actions, or in regular Java classes. However, to tie all these components together, you sometimes need additional code embedded in the JSP pages themselves. Recall from Chapter 3, that JSP lets you put actual Java code in pages using a set of scripting elements. In this chapter we look at how you can use these scripting elements and when it makes sense to do so.
We start with a brief introduction to the Java language constructs you're likely to use in a JSP page. If you already know Java by heart you can safely skip the first section. But if you have never written a Java program, or are still a "newbie," you should read it carefully. Don't expect to become a Java guru after reading this introduction, of course. The Java language, combined with the standard libraries, provides many powerful features not covered here. To learn more about Java, I recommend that you read one of the many books dedicated to the language and its libraries, for instance Java in a Nutshell and Java Examples in a Nutshell, both by David Flanagan (O'Reilly).
You don't have to be a Java expert to develop JSP pages, but it helps to have an understanding of the basic concepts. This overview of the Java language and some of the standard classes should be enough to get you started.
Java is an object-oriented language. This means that everything in Java is an object, except for a few primitive types such as numbers, characters, and Boolean values. An object is an instance of a class, which serves as a source code template describing how the object should behave. It's helpful to think of a class as a blueprint from which identical copies (objects) are created. Example 6.1 shows a simple Java class.
Example 6.1. Simple Java Class
/**
 * This is just a simple example of a Java class
 * with two instance variables, a constructor, and 
 * some methods.
 */

public class Rectangle {

  // Data
  private int width;
  private int height;

  // Constructor
  public Rectangle(int w, int h) {
    width = w;
    height = h;
  }

  // Methods
  public int getWidth( ) {
    return width;
  }

  public void setWidth(int w) {
    width = w;
  }

  public int getHeight( ) {
    return height;
  }

  public void setHeight(int h) {
    height = h;
  }

  public double getArea( ) {
    double area;

    area = width * height;
    return area;
  }

}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Java Primer
You don't have to be a Java expert to develop JSP pages, but it helps to have an understanding of the basic concepts. This overview of the Java language and some of the standard classes should be enough to get you started.
Java is an object-oriented language. This means that everything in Java is an object, except for a few primitive types such as numbers, characters, and Boolean values. An object is an instance of a class, which serves as a source code template describing how the object should behave. It's helpful to think of a class as a blueprint from which identical copies (objects) are created. Example 6.1 shows a simple Java class.
Example 6.1. Simple Java Class
/**
 * This is just a simple example of a Java class
 * with two instance variables, a constructor, and 
 * some methods.
 */

public class Rectangle {

  // Data
  private int width;
  private int height;

  // Constructor
  public Rectangle(int w, int h) {
    width = w;
    height = h;
  }

  // Methods
  public int getWidth( ) {
    return width;
  }

  public void setWidth(int w) {
    width = w;
  }

  public int getHeight( ) {
    return height;
  }

  public void setHeight(int h) {
    height = h;
  }

  public double getArea( ) {
    double area;

    area = width * height;
    return area;
  }

}
It's important to remember that a class always defines two items:
  • data : a collection of information in an object
  • methods : a set of functions that act on that data

Section 6.1.1.1: Data

Data, often called variables, can consist of primitive datatypes such as integers, Booleans, and floating-point values (both the width and height in this example are integers, represented by the keyword
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Implicit JSP Objects
When you use scripting elements in a JSP page, you always have access to a number of objects (listed in Table 6.1) that the JSP container makes available. These are called implicit objects. These objects are instances of classes defined by the servlet and JSP specifications. Appendix B, contains complete descriptions of all methods for each class, and we will cover them in more detail as we move through the book. However, I want to briefly introduce them here, as they are used in a number of examples throughout this book.
Table 6.1: Implicit JSP Objects
Variable Name
Java Type
request
javax.servlet.http.HttpServletRequest
response
javax.servlet.http.HttpServletResponse
pageContext
javax.servlet.jsp.PageContext
session
javax.servlet.http.HttpSession
application
javax.servlet.ServletContext
out
javax.servlet.jsp.JspWriter
config
javax.servlet.ServletConfig
page
java.lang.Object
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Conditional Processing
In most web applications, you produce different output based on runtime conditions, such as the state of a bean or the value of a request header such as UserAgent (containing information about the type of client that is accessing the page).
If the differences are not too great, you can use JSP scripting elements to control which parts of the JSP page are sent to the browser, generating alternative outputs from the same JSP page. However, if the outputs are completely different, I recommend using a separate JSP page for each alternative and passing control from one page to another. This chapter contains a number of examples in which one page is used. In the remainder of this book you'll see plenty of examples where multiple pages are used instead.
In Chapter 5, you saw how to use the <jsp:getProperty> and the <jsp:setProperty> actions to access a bean's properties. However, a bean is just a Java class that follows certain coding conventions, so you can also call its methods directly.
Briefly, a bean is a class with a constructor that doesn't take an argument. This makes it possible for a tool, such as the JSP container, to create an instance of the bean class simply by knowing the class name. The other condition of a bean that we are concerned with is the naming of the methods used to access its properties. The method names for reading and writing a property value, collectively known as the bean's accessor methods, must be composed of the keywords get and set, respectively, plus the name of the property. For instance, you can retrieve the value of a property named month in a bean with the method getMonth( ) and set it with the method setMonth( ). Individually, the accessor method for reading a property value is known as the getter method, and the accessor method for writing a property value is the setter
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Displaying Values
Besides using scriptlets for conditional output, one more way to employ scripting elements is by using a JSP expression element to insert values into the response. A JSP expression element can be used instead of the <jsp:getProperty> action in some places, but it is also useful to insert the value of any Java expression that can be treated as a String.
An expression starts with <%= and ends with %>. Note that the only syntax difference compared to a scriptlet is the equals sign (=) in the start identifier. An example is:
<%= userInfo.getUserName( ) %>
The result of the expression is written to the response body. One thing is important to note: as opposed to statements in a scriptlet, the code in an expression must not end with a semicolon. This is because the JSP container combines the expression code with code for writing the result to the response body. If the expression ends with a semicolon, the combined code will not be syntactically correct.
In the final example of Chapter 5, we used <jsp:getProperty> actions to fill out the form fields with UserInfoBean values. To recap, it looked like this:
<tr>
  <td>Name:</td>
  <td><input type="text" name="userName" 
    value="<jsp:getProperty
             name="userInfo"
             property="userNameFormatted"
           />">
  </td>
</tr>
In this case, the <jsp:getProperty> syntax is distracting, since it's used as the value of an HTML element. You can use expressions to make the user input form page easier to read. The following example shows the same part of the page with the <jsp:getProperty> action replaced with an expression:
<tr>
  <td>Name:</td>
  <td><input type="text" name="userName"
    value="<%= userInfo.getUserNameFormatted( ) %>" >
  </td>
</tr>
The result is exactly the same, but this is more compact.
Expressions help you write more compact code, but they can also help you with something even more important. The UserInfoBean provides a set of properties with values formatted for HTML output; that's what we used in Chapter 5 to avoid confusing the browser with special characters in the bean property values. However, it's much easier to reuse a bean if it doesn't need to format its property values for a certain type of output. With expressions, we can let the bean be ignorant of how its property values are used, and use a utility class to do the formatting instead, as in Example 6.5.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using an Expression to Set an Attribute
Content preview·