|
|
|
|
JavaServer Pages, 2nd EditionBy Hans Bergsten2nd Edition August 2002 0-596-00317-X, Order Number: 317X 684 pages, $44.95 US $69.95 CA £31.95 UK |
Chapter 3
JSP OverviewJSP 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.
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</h2>");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( )andsaveOrderInfo( )), and also generates the response HTML code, embedded directly in the servlet code usingprintln( )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.
- It's hard to take advantage of web-page development tools when designing the application interface. If such tools are used to develop the web page layout, the generated HTML must then be manually embedded into the servlet code, a process which is time consuming, error prone, and extremely boring.
Adding JSP to the puzzle lets you solve these problems by separating the request processing and business logic code from the presentation, as illustrated in Figure 3-1. Instead of embedding HTML in the code, you place all static HTML in a JSP page, just as in a regular web page, and add a few JSP elements to generate the dynamic parts of the page. The request processing can remain the domain of the servlet, and the business logic can be handled by JavaBeans and EJB components.
Figure 3-1. Separation of request processing, business logic, and presentation
![]()
As I mentioned before, separating the request processing and business logic from presentation makes it possible to divide the development tasks among people with different skills. Java programmers implement the request processing and business logic pieces, web page authors implement the user interface, and both groups can use best-of-breed development tools for the task at hand. The result is a much more productive development process. It also makes it possible to change different aspects of the application independently, such as changing the business rules without touching the user interface.
This model has clear benefits even for a web-page author without programming skills, working alone. A page author can develop web applications with many dynamic features, using the JSP standard actions and the JSTL libraries, as well as Java components provided by open source projects and commercial companies.
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.
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.
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 in one package under the name web container.
So in a way, a JSP page is really just another way to write a servlet without having to be a Java programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular servlet: it's loaded once and called repeatedly, until the server is shut down. By virtue of being an automatically generated servlet, a JSP page inherits all the advantages of a servlet described in Chapter 2: platform and vendor independence, integration, efficiency, scalability, robustness, and security.
JSP Elements
There are three types of JSP elements you can use: directive, action, and scripting.
Directive elements
The directive elements, shown in Table 3-1, specify information about the page itself that remains the same between requests--for example, if session tracking is required or not, buffering requirements, 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 session tracking, error page, and buffering requirements
<%@ include ... %>
Includes a file during the translation phase
<%@ taglib ... %>
Declares a tag library, containing custom actions, that is used in the page
Standard action elements
Action elements typically perform some action based on information that is required at the exact time the JSP page is requested by a browser. An action can, for instance, access parameters sent with the request to do a database lookup. It can also dynamically generate HTML, such as a table filled with information retrieved from an external system.
The JSP specification defines a few standard action elements, listed in Table 3-2.
Table 3-2: Standard action elements Action element
Description
<jsp:useBean>
Makes a JavaBeans component available in a page
<jsp:getProperty>
Gets a property value from a JavaBeans component and adds it to the response
<jsp:setProperty>
Sets a JavaBeans component property value
<jsp:include>
Includes the response from a servlet or JSP page during the request processing phase
<jsp:forward>
Forwards the processing of a request to servlet or JSP page
<jsp:param>
Adds a parameter value to a request handed off to another servlet or JSP page using
<jsp:include>or<jsp:forward><jsp:plugin>
Generates HTML that contains the appropriate browser-dependent elements (OBJECT or EMBED) needed to execute an applet with the Java Plug-in software
Custom action elements and the JSP Standard Tag Library
In addition to the standard actions, the JSP specification includes a Java API a programmer can use to develop custom actions to extend the JSP language. The JSP Standard Tag Library (JSTL) is such an extension, with the special status of being defined by a formal specification from Sun and typically bundled with the JSP container. JSTL contains action elements for processes needed in most JSP applications, such as conditional processing, database access, internationalization, and more. This book covers all the JSTL actions in detail.
If JSTL isn't enough, programmers on your team (or a third party) can use the extension API to develop additional custom actions, maybe to access application-specific resources or simplify application-specific processing. The examples in this book use a few custom actions in addition to the JSTL actions, and three chapters in Part III are dedicated to custom action development.
Scripting elements
Scripting elements, shown in Table 3-3, allow you to add small pieces of code (typically Java code) in a JSP page, such as an
ifstatement to generate different HTML depending on a certain condition. Like actions, they are also executed when the page is requested. You should use scripting elements with extreme care: if you embed too much code in your JSP pages, you will end up with the same kind of maintenance problems as with servlets embedding HTML.
Table 3-3: Scripting elements Element
Description
<% ... %>
Scriptlet, used to embed scripting code.
<%= ... %>
Expression, used to embed scripting code expressions when the result shall be added to the response. Also used as request-time action attribute values.
<%! ... %>
Declaration, used to declare instance variables and methods in the JSP page implementation class.
JavaBeans components
JSP elements, such as action and scripting elements, are often used to work with JavaBeans. Put succinctly, a JavaBeans component is a Java class that complies with certain coding conventions. JavaBeans components are typically used as containers for information that describes application entities, such as a customer or an order.
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.
This MVC model is used for most of the examples in this book. In Part II, JSP pages are used as both the Controller and the View, and JavaBeans components are used as the Model. The examples in Chapters 5 through 9 use a single JSP page that handles everything, while Chapters 10 through 13 show how you can use separate pages for the Controller and the View to make the application easier to maintain. Many types of real-world applications can be developed this way, but what's more important is that this approach allows you to examine all the JSP features without getting distracted by other technologies. In Part III, we look at other possible role assignments when JSP is combined with servlets and Enterprise JavaBeans.
Back to: JavaServer Pages, 2nd Edition
© 2001, O'Reilly & Associates, Inc.
webmaster@oreilly.com