BUY THIS BOOK

Safari Books Online

What is this?

Looking to Reprint this content?


JavaServer Pages
JavaServer Pages, Second Edition By Hans Bergsten
August 2002
Pages: 684

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, JAXP™ for XML processing, and JTA™ (Java Transaction API) for performing atomic transactions. In addition, J2EE also 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 primarily about JavaServer Pages, covering the latest version of this technology, JSP 1.2, as well as the related JSP Standard Tag Library (JSTL) Version 1.0. It also covers other J2EE technologies, such as servlets and JDBC, with focus on how to combine them with JSP in the most efficient way.
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, this functionality is key to web applications such as online shopping and employee directories, as well as for personalized and internationalized content.
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, this functionality is key to web applications such as online shopping and employee directories, as well as for personalized and internationalized content.
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 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 that are 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. One such set of commonly needed custom elements is defined by a specification related to the JSP specification: the JSP Standard Tag Library (JSTL) specification. 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 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 special active elements into HTML pages. These elements look similar to HTML elements, but behind the scenes they are actually componentized Java programs that the server executes when a user requests the page. Here's a simple JSP page that illustrates this:
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<html>
  <body bgcolor="white">
  
  <jsp:useBean id="clock" class="java.util.Date" />
                  <c:choose>
                  <c:when test="${clock.hours < 12}">
      <h1>Good morning!</h1>
    </c:when>
                  <c:when test="${clock.hours < 18}">
      <h1>Good day!</h1>
    </c:when>
                  <c:otherwise>
      <h1>Good evening!</h1>
    </c:otherwise>
                  </c:choose>
  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 P.M., "Good day!" if between 12 P.M. and 6 P.M., and "Good evening!" otherwise. When a user asks for this page, the JSP-enabled web server executes the logic represented by the highlighted JSP elements and creates an HTML 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 run through what you need to run the examples and develop your own applications. You really only need 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.2-enabled web server, such as Apache Tomcat from the Jakarta Project
The Apache Tomcat server is the reference implementation for JSP 1.2. All the examples in the book were tested on Tomcat. In Chapter 4, I'll show you how to download, install, and configure the Tomcat server as well as the examples described in this book.
In addition, there are a 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 IDEs and authoring tools with varying degrees of JSP support are listed on Sun's JSP web site (http://java.sun.com/products/jsp). 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 is 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. You'll 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 off this chapter by defining the term web application. We've all seen regular client-side applications, but what exactly is a web application? Loosely, it can be defined as an application running on a server a user accesses through a thin, general-purpose client. Today, the most common client is a web browser on a PC or workstation, but other kinds of clients are rapidly joining the party, such as wireless PDAs, cell phones, and other specialized devices.
The lofty goal here is to access all the information and services you need from any type of device that happens to be 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. A basic understanding of HTTP is key to developing 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 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 focus on. As you 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. To really understand and use the full power of JSP, you need to know a fair bit about servlets. Hence, we'll take a look at servlet fundamentals in the last section of this chapter.
HTTP and all extended protocols based on HTTP are based on a very simple 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 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 resource (or a response with an error message if it can't deliver the resource for some reason). A resource can be a number of things, such as a simple HTML file returned verbatim to the browser or a program that generates the response dynamically. This request/response model is illustrated in Figure 2-1.
Figure 2-1: HTTP request/response with two resources
This simple model implies three important facts you need to be aware of:
  • HTTP is a stateless protocol. This means that the server doesn't keep any information about the client after it sends its response, and therefore can't recognize that multiple requests from the same client may be related.
  • Web applications can't 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.
  • There's nothing in the protocol that tells the server how a request is made; consequently, the server can't distinguish between various methods of triggering the request on the client. For example, the HTTP protocol doesn't 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
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. 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.
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
All the major web servers and application servers support servlets, so a servlet-based solution doesn't tie you to one specific vendor. And, since 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 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.
Efficiency
Servlets execute in a process that is running until the servlet-based application is shut down. Each servlet request is executed as a separate thread in this permanent process. This is far more efficient that the CGI model, where a new process is created for each request. First of all (and most obvious), a servlet doesn't have the overhead of creating the process and loading the CGI script and possibly its interpreter. But another timesaver is that servlets can also access resources that remain loaded in the process memory between requests, such as database connections and persistent state.
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 the server processes a JSP page.
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. However, when the application grows into something bigger (spanning multiple pages, using external resources such as databases, 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 as an important part 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. Example 3-1 shows how a servlet class often looks.
Example 3-1. A typical servlet class
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. Example 3-1 shows how a servlet class often looks.
Example 3-1. A typical servlet class
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. Even so, the pure servlet-based approach still has a few problems:
  • Thorough 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 that differ for each request, as shown in Figure 3-2.
Figure 3-2: Template text and JSP elements
Everything in the page that isn't a JSP element is called template text. Template text can 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 use HTML, 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.
When a JSP page request is processed, the template text and dynamic content generated by the JSP elements are merged, and the result is sent as the response to the browser.
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
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 responsible for intercepting requests for JSP pages. To process all JSP elements in the page, the container first turns the JSP page into a servlet (known as the [ JSP page implementation class). The conversion is pretty straightforward; all template text is converted to println( ) statements similar to the ones in the handcoded servlet shown in Example 3-1, and all JSP elements are converted to Java code that implements the corresponding dynamic behavior. The container then compiles the servlet class.
Converting the JSP page to a servlet and compiling the servlet form the translation phase. The JSP container initiates the translation phase for a page automatically when it receives the first request for the page. Since the translation phase takes a bit of time, the first user to request a JSP page notices a slight delay. The translation phase can also be initiated explicitly; this is referred to as precompilation of a JSP page. Precompiling a JSP page is a way to avoid hitting the first user with this delay. It is discussed in more detail in Chapter 16.
The JSP container is also responsible for invoking the JSP page implementation class (the generated servlet) 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 request goes straight to the request processing phase (i.e., the container 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, I introduce a design model called Model-View-Controller (MVC), suitable for both simple and complex applications.
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 logic 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, such as customer, product, and order information. Presentation refers to how the application data is displayed to the user, for example, 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, 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 many web sites go 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 the 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.2, 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 4 is a pure Java web server with support for the Servlet 2.3 and JSP 1.2 specifications. In order 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 download and install the Java 2 SDK, as opposed to the slimmed-down Runtime Environment (JRE) distribution. The reason is that JSP requires a Java compiler, 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 separately, 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.3.1_01 and v1.4. I suggest 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 4 is a pure Java web server with support for the Servlet 2.3 and JSP 1.2 specifications. In order 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 download and install the Java 2 SDK, as opposed to the slimmed-down Runtime Environment (JRE) distribution. The reason is that JSP requires a Java compiler, 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 separately, 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.3.1_01 and v1.4. I suggest 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:
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 per platform, but is typically easy to do. Just follow the instructions on the web site where you download the SDK.
Before you install and run Tomcat, make sure that the JAVA_HOME environment variable is set to the installation directory of your Java environment, and that the Java
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 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 for running the examples in this book and to develop your own applications. If you're a Java programmer and are interested in seeing how Tomcat is implemented, feel free to download the source as well and take a look at the internals.
The binary distribution is available at http://jakarta.apache.org/site/binindex.html.
On this page you find three types of builds: release builds, milestone builds, and 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 aren't 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.
I recommend that you download the latest release build. All examples in this book were developed and tested using the 4.0.4 version, but any release later than 4.0.4 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
How to continue from here varies a bit depending on your platform.
For Windows, select jakarta-tomcat-4.0.4.zip and save it to your hard drive, for instance in a directory named C:\Jakarta. You can unpack the package either with a ZIP utility program, such as
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
The Tomcat installation directory contains a number of subdirectories. All of them are described in the README.txt file, but the most important ones are:
bin
Scripts for starting and stopping the Tomcat server.
conf
Tomcat configuration files.
webapps
Default l ocation for web applications served by Tomcat.
Two more subdirectories under the Tomcat home directory are created the first time you start the server:
logs
Server log files. If something doesn't work as expected, look in the files in this directory for clues as to what's wrong.
work
A directory for temporary files created by the JSP container and other files. This directory is where the servlets generated from JSP pages are stored.
To test the server, run the startup script as described in the platform-specific sections, and (assuming you're running Tomcat on the same machine as the browser and that you're using the default 8080 port for Tomcat) open a browser and enter this URL in the Location/Address field: http://localhost:8080/.
The Tomcat main page is shown in the browser, as in Figure 4-2, and you can now run all servlet and JSP examples bundled with Tomcat to ensure everything works.
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 examples can be downloaded from the O'Reilly site http://www.oreilly.com/catalog/jserverpages2/ .
They can also be downloaded from the book web site that I maintain:
http://www.TheJSPBook.com/examples/jspbook.zip
The file that contains all examples, accessible from this page, 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, servlets, and utility classes used in the examples.
The examples directory structure complies with the standard Java web application format described in Chapter 2. You can therefore configure any Servlet 2.3-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 for instructions on how to install a web application.
To install the example application for Tomcat, simply 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 %CATALINA_HOME%\webapps\ora
            
On a Unix platform it looks like this:
[hans@gefion jspbook] cp -R ora $CATALINA_HOME/webapps
            
Recall from Chapter 2 that each web application in a server is associated with a unique URI prefix (the context path). When you install an application in Tomcat's webapps directory, the subdirectory name is assigned automatically as the URI prefix for the application (that is,
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. All servers compliant with the Servlet 2.2 specification (or later) supports this file structure, so you can use the example application as a guideline when you create your own web applications. How a web application is installed isn't 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 where they belong and let you configure the application using a special tool or through web-based forms.
If you look in the ora web application directory, you 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, and a classes directory. We will look at this in much more detail later, starting in Chapter 5, but here's a quick review:
  • The web.xml file contains configuration information for the example application in the format defined by the servlet 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 specification. A very 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, 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 them all -- standard actions, custom actions, the JSP Standard Tag Library, JavaBeans, and scripting elements. Before going into all of that, however, let's start with a simple example to get a better feel for how the basic JSP elements work.
Recall from Chapter 3 that a JSP page is just a regular HTML page with a few special elements. A JSP page 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 just need a regular text editor such as Notepad on Windows or Emacs on Unix. There are 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 (IDE) even include a small web container that allows you to easily execute and debug the pages during development. There are also several web-page authoring tools -- the type of tools often used when developing regular HTML pages -- that supports JSP to some degree. You can browse through a fairly extensive list of tools like this at my web site: http://TheJSPBook.com/. I recommend that you do not use them initially, though; 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 easy.jsp, is shown in Example 5-1.
Example 5-1. JSP page showing a dynamically calculated sum (easy.jsp)
                  <%@ page contentType="text/html" %>
                  <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating a JSP Page
Recall from Chapter 3 that a JSP page is just a regular HTML page with a few special elements. A JSP page 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 just need a regular text editor such as Notepad on Windows or Emacs on Unix. There are 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 (IDE) even include a small web container that allows you to easily execute and debug the pages during development. There are also several web-page authoring tools -- the type of tools often used when developing regular HTML pages -- that supports JSP to some degree. You can browse through a fairly extensive list of tools like this at my web site: http://TheJSPBook.com/. I recommend that you do not use them initially, though; 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 easy.jsp, is shown in Example 5-1.
Example 5-1. JSP page showing a dynamically calculated sum (easy.jsp)
                  <%@ page contentType="text/html" %>
                  <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<html>
  <head>
    <title>JSP is Easy</title>
  </head>
  <body bgcolor="white">
  
    <h1>JSP is as easy as ...</h1>
  
    <%-- Calculate the sum of 1 + 2 + 3 dynamically --%>
    1 + 2 + 3 = <c:out value="${1 + 2 + 3}" />
  
  </body>
</html>
The easy.jsp page displays static HTML plus the sum of 1, 2, and 3, calculated at runtime and dynamically added to the response. We'll look at all the different pieces soon, but first you may want to run the example to see how it works.
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 a JSP Page
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, an application with all these components had to be installed and configured in different ways for different servers, making it hard for web application developers to provide easy-to-use installation instructions and tools.
Starting with the Servlet 2.2 specification, there's a standard, portable way to package all web application resources, along with a deployment descriptor. The deployment descriptor is a file named web.xml, containing information about security requirements, how all the resources fit together, and other facts about the application. The deployment descriptor and all the other web application files are placed in a WAR file, arranged in a well-defined hierarchy. 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 file format is used for both JAR and ZIP files).
Having a standardized web application format lets container vendors develop installation and configuration tools that make it easy to install an application. During installation, the container is free to unpack the contents of the WAR 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.
Even though a container is required to know how to deal only with applications packaged as a WAR file, most (if not all) containers also let you store your application files directly in a filesystem using the same file structure as is defined for the WAR file. During development, it's more convenient to work with the files in a regular filesystem structure instead of creating an updated WAR file every time you make a change. In Tomcat 4, for instance, any subdirectory under the webapps directory is assumed to be a web application, using the standard web application file structure.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Running a JSP Page
Assuming you have installed all book examples as described in Chapter 4, first start the Tomcat server and load the book examples main page by typing the URL http://localhost:8080/ora/index.html in the browser address field. Note how the /ora part of the URL matches the Tomcat webapps subdirectory name for the example application. This part of the URL is called the application's context path; every web application has a unique context path, assigned one way or another when you install the application. Tomcat 4 uses the subdirectory name as the context path by default, but other containers may prompt you for a path in an installation tool or use other conventions. When you make a request for a web application resource (an HTML or JSP page, or a servlet), the first part of the URL (after the hostname and port number) must be the context path, so the container knows which application should handle the request.
There's one exception to this rule; one application per container may be installed as the default, or root, application. For Tomcat 4, this application in stored in the webapps/ROOT directory, by default. Requests for resources in the default application don't start with a context path (or more accurately, have an empty string as their context path). For instance, the http://localhost:8080/index.html URL is used to request a page in the default application.
You can run Example 5-1 by clicking the "JSP is Easy" link from the book examples main page, shown in Figure 5-1. You should see a result like the one shown in Figure 5-2.
Figure 5-1: JSP book examples main page
Figure 5-2: The "JSP is Easy" example output
The page shown in Example 5-1 contains both regular HTML elements and JSP elements. If you use the View Source function in your browser, you notice that none of the JSP elements are visible in the page source. That's because the server processes the JSP elements when the page is requested, and only the resulting output is sent to the browser. The HTML elements, on the other hand, are sent to the browser as-is, defining the layout of the page. To see the unprocessed JSP page in a separate window, you can click on the source link for 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!
Using JSP Directive Elements
Let's look at each piece of Example 5-1 in detail. The first two lines are JSP directive elements. Directive elements specify attributes of the page itself, such as the type of content produced by the page, page buffering requirements, declaration of other resources used by the page, and how possible runtime errors should be handled. Hence, a directive doesn't directly affect the content of the response sent to the browser. There are three different JSP directives: page, include, and taglib. In this chapter, we're using the page and the taglib directives. The include directive is described in Chapter 16.
JSP pages typically starts with a page directive that specifies the content type for the page:
<%@ page contentType="text/html" %>
A JSP directive element starts with a directive-start identifier (<%@), followed by the directive name (page in this case), directive attributes, and ends with %>. A directive contains one or more attribute name/value pairs (e.g., contentType="text/html"). Note that JSP element and attribute names are case-sensitive, and in most cases, the same is true for attribute values. All attribute values must also be enclosed in single or double quotes.
The page directive has many possible attributes. In Example 5-1, only the contentType attribute is used. It specifies the MIME-type for the content the page produces. The most common values are text/html for HTML content and text/plain for preformatted, plain text. But you can also specify other types, such as text/xml for browsers that support XML or text/vnd.wap.wml for devices such as cell phones and PDAs that have built-in WML browsers. The container sends the content type information to the browser as a response header called Content-Type, so the browser knows how to interpret and render the page. If you omit the contentType attribute, the container sets the header to text/html.
Some of the other page directive attributes you may use from time to time are
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 Template Text
Besides JSP elements, notice that the easy.jsp page contains mostly regular HTML, highlighted in Example 5-2.
Example 5-2. JSP page template text
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<html>
                  <head>
                  <title>JSP is Easy</title>
                  </head>
                  <body bgcolor="white">
                  <h1>JSP is as easy as ...</h1>
    <%-- Calculate the sum of 1 + 2 + 3 dynamically --%>
    1 + 2 + 3 = <c:out value="${1 + 2 + 3}" />
  </body>
                  </html>
               
In JSP parlance, this is called template text. Everything that's not a JSP element (i.e., not a directive, action, or scripting element) is template text. Template text is sent to the browser as-is. This means you can use JSP to generate any type of text-based output, such as XML, WML, or even plain text. The JSP container doesn't care what the template text represents.
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 JSP Action Elements
Besides the fixed template text, the easy.jsp page also produces dynamic content. It has very simple dynamic content -- the sum of 1, 2 and 3 calculated at runtime -- but step back a moment and think about the type of dynamic content you see on the Web every day. Common examples might be a list of web sites matching a search criterion on a search engine site, the content of a shopping cart on an e-commerce site, a personalized news page, or messages in a bulletin board. The actual data for the dynamic content can come from many types of sources, for instance from a database, an XML document, or data accumulated in memory based on previous requests. The dynamic data needs to be combined with regular HTML elements into a page with the right layout, navigation bars, the company logo, and so forth, before it's sent to the browser. When using JSP, the regular HTML is the template text described earlier, and the dynamic data is inserted at the appropriate place in the template text using a JSP action element.
A JSP action is executed when a JSP page is requested (this is called the request processing phase, as you may recall from Chapter 3). In other words, JSP action elements represent dynamic actions that take place at runtime, as opposed to JSP directives, which are used only during the translation phase (when the JSP page is turned into Java servlet code). An action can add text to the response, as in the example used in this chapter, but it can also do other things such as write to a file on the server, send an email, or retrieve data from a database that is later added to the response by other actions. Example 5-3 shows the easy.jsp page again, this time with the JSP action element highlighted.
Example 5-3. JSP action elements
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<html>
  <head>
    <title>JSP is Easy</title>
  </head>
  <body bgcolor="white">
  
    <h1>JSP is as easy as ...</h1>
  
    <%-- Calculate the sum of 1 + 2 + 3 dynamically --%>
    1 + 2 + 3 = 
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 JavaBeans Components in JSP Pages
The JavaBeans specification defines a set of programming conventions for Java classes that should be used as pluggable components. In layman's terms, tools that have no inside information about a class can use it if it's developed according to these conventions. For instance, a GUI builder tool can support widgets developed as JavaBeans components. A JavaBeans component, or just a bean for short, is often used in JSP as the container for the dynamic content to be displayed by a web page. It typically represents something specific, such as a person, a product, or a shopping order. When JSP is combined with servlets, the bean can be created and initialized with data by the servlet and passed to a JSP page that simply adds the bean's data to the response. But even in a pure JSP application, a bean is a useful tool, for instance for capturing and validating user input.
A programmer must develop the bean, but someone who doesn't have any programming experience can then use it in a JSP page. JSP defines a number of standard actions for working with beans, and the JSTL Expression Language accepts beans as variables in expressions. In this chapter, we take a closer look at what a bean is and how it can produce dynamic content in a page. We'll return to beans in Chapter 8 to see how they can be used for input validation.
As I said earlier, a bean is simply a Java class that follows certain coding conventions, so it can be used by tools as a component in a larger application. It can be instantiated and made available to the JSP page in a couple of ways. In an application that uses a servlet as a frontend for all business logic, the bean is typically created by the business logic code and sent to the JSP page to include its contents in the response. I describe this approach in detail in Chapter 18 and Chapter 19. The bean can also be created directly by a JSP page. This is the approach used in this chapter.
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 a Bean?
As I said earlier, a bean is simply a Java class that follows certain coding conventions, so it can be used by tools as a component in a larger application. It can be instantiated and made available to the JSP page in a couple of ways. In an application that uses a servlet as a frontend for all business logic, the bean is typically created by the business logic code and sent to the JSP page to include its contents in the response. I describe this approach in detail in Chapter 18 and Chapter 19. The bean can also be created directly by a JSP page. This is the approach used in this chapter.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Declaring a Bean in a JSP Page
Content preview·