You are on page 1of 8
THE EXPERT'S VOICE® IN JAVA Dra i , riv »o= oe | | | @.) m | mm } | Se ees LT he , A comprehensive guide to JSP including expression language, tags, data access, filtering, security, and integration with JSE FOURTH EDITION Pro JSP 2, Fourth Edition Gopyright © 2005 by Simon Brown, Sam Dalton, Daniel Jepp, Dave Johnson, Sing Li, and Matt Raible All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher, ISBN (pbk): 1-59059-513-0 Printed and bound in the United States of Ameriea 987654321 ‘Trademarked names may appear in this book, Rather than use a trademark symbol with every occurrence of atrademarked name, we use the names only in an editorial fashion and to the benefit ofthe trademark owner, with no intention of infringement of the trademark, Lead Editors: Steve Anglin and Kevin Mukhar Technical Reviewers: Scott Davis and Dilip Thomas Editorial Board: Steve Anglin, Dan Appleman, Ewan Buckingham, Gary Cornell, Tony Davis, Jason Gilmore, Jonathan Hassell, Cheis Mills, Dominic Shakeshaft, im Sumser Associate Publisher: Grace Wong Project Manager: Beckie Brand Copy Edit Manager: Nicole LeGlere Copy Editor: Sharon Wilkey Assistant Production Director; Kari Brooks-Gopony Production Editor: Ellie Fountain Compositor: ContentWorks Proofreader: Sue Boshers Indexer: Julie Grady Artist: Kinetic Publishing Services, LLC Interior Designer: Van Winkle Design Group Cover Designer: Kust Krames Manufacturing Director: Tom Debolski Distributed to the book trade worldwide by Springer-Verlag New York, Inc.,233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-nyspringer-sbm.com, or visit http: //wow .springeronline..com, For information on translations, please contact Apress directly at 2560 Ninth Street, Suite 219, Berkeley, CA 24710, Phane 510-549-5930, fax 510-549-0939, e-mail infoPapress.-com, ar visit http ://mm. apress.com. The information in this book is distributed on an“as is” basis, without warranty. Although every precau- tion has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liabitity to any person or entity with respect to any lass or damage caused or alleged to be caused directly or indirectly by the information contained in this work. ‘The source code for this book is available to readers at https //uw. apress.com in the Saurce Code section, CHAPTER 1 © THE ANATOMY OF A JAVASERVER PAGE (commonly known asa taglib) is simply a collection af one or mare custom tags that are gener- ally related in some way. For example, as we said earlier, the JSP 2.0 specification introduced a standard tag library known as the JSTL. The ISP 2.1 specification refines the ISTL. The JSTLs core library contains tags that salve many of the common and recurring problems encountered when building JSP-based web applications. After the tags are bundled into a tag library, that tag library can be reused across the following: + Asingle page + The pages ofa web application * Different web applications The ability to easily reuse custom tags across more than a single page illustrates the true potential of tag libraries when building Web applications. This is something that you'll be seeing when you examine the best practices for designing and building custom tags in later chapters Readability Another important best practice is that of readability, Embedding too much Java code in the page can easily lead to pages that are unreadable as content (typically HTMI) is mixed with ISP tags and Java code wrapped up as scriptlets. In addition to the confusion caused by the various syntaxes that each of these “languages” uses, one clear problem with embedding Java code inside JSP pages is that it’s hard to correctly indent your source code. Writing and indent- ing code is trivial when dealing with regular class files, but trying to correctly indent Java code that is mixed with HTML and JSP elements is a different sto Wrapping up reusable functionality as custom tags or JavaBeans components removes this code from the page, therefore making it cleaner, shorter, and more readable. Also, choosing appropriate names for your custom tags can make a page more readable by page designers— those who are responsible for the look and feel of a page rather than the mechanics of howit works. This, as you'll see when we talk about some of the best practices associated with custom tags, is very important and often overlooked, Maintainability Having a system that promotes reusability and readability is great, but what does that mean in the real world? The maintainability of an application is how well the system can be modified and fixed during its lifetime, which for a given application is typically hard to measure. How- ever, in looking at any system, several signs help us to identify whether that system will be easy or difficult to maintain, In reality, this is dictated by reuse and the need to ensure that the code is as readable as possible—the two goals that custom tags can help you achieve, JavaServer Pages Application Architecture All the factors mentioned in this chapter—reusability, readability, maintainability—are improved by a good design or architecture; therefore, it’s worth ensuring that sufficient time is taken early in your project life cycle to select the architecture that best suits your envirenment CHAPTER 1 © THE ANATOMY OF A JAVASERVER PAGE and technologies. Although architecture and design can seem a little daunting at first (espe- cially when you're new to the technology and all you really want to dais cut code), with a little effort you'll soon start to understand the benefits that are to be gained by using tried and tested patterns Asyou're no doubt aware, the Java EE 5 presentation tier consists of several components— for example, servlets, [SP pages, tag libraries, and JavaBeans—which may be used to create a presentation layer fora web application, All these components have their relative strengths and weaknesses, particularly when used in different combinations. Good design, therefore, is con- cerned not only with selecting the correct component for a task but also with ensuring that the componentis used in the correct manne. In recent times, two papular web-application architectures have been repeatedly used for web-application design, and there are strengths and weaknesses to consider with both, Let's discuss the simpler of these two architectures first. Model 1 Architecture The simplicity of the Madel | architecture is that each JSP page is entrusted to deal with its request entirely by itself, thereby generating a response and sending it back to the client, and for this reasan it’s often known as page-centrie, Usually such JSP pages will use some form of model to represent the business logic of the application. JavaBeans components are often used to model business logic. The JavaBean neatly encapsulates the business logic for reusability and at the same time keeps the amount of processing logic in the page to a minimum, Figure 1-3 shows a ISP page entrusted with handling a cli nt request and building an appropriate response all by itself. [tis also using a JavaBean to encapsulate business logic. ,—Piservet Container. Datta Ter Request moo Figure 1-3. [n a Moet 1 architecture, all the application processing occurs in a single tier of the application, rover Response Each JSP page has the potential to contain a lot of processing logic, However, as long as the application is relatively small with few pages, the Model 1 architecture isa good choice because it's quick and simple to put together. However, such a page-centric architecture ean begin to introduce problems when used with larger, more complex applications. Some of the more common problems are outlined here. 10 CHAPTER 1 © THE ANATOMY OF A JAVASERVER PAGE Maintainability Problems Because each JSP page is solely responsible for handling a client request, it will often have to directly interact with a business layer. This can resultin the application structure being embodied within the pages themselves. This obviously makes the pages more complicated and more likely to contain lots of scriptlet code, which ultimately makes them far harder to maintain. Reusability Problems When most of the processing logic is embedded into the JSP pages, it becomes much more difficult to reuse common functionality because it’s usually implemented using scriptlets. Often this results in alot of cutting and pasting of code that isn't only bad from a reusability perspective but is also likely to introduce errors and decrease productivity. Security Problems Because each JSP page is responsible for handling all of its processing, it’s possible that any actions that require a user to be logged in or that access password-protected resources sch as databases could end up exposing sensitive information by embedding it in the page. Its there- fore important to make sure that any such logic is encapstilated into JavaBeans components or custom actions to prevent this possible security hole, Of course it would make far more sense to provide such security controls via a single, centralized access point, and you will see how the next architecture up for discussion does exactly this. Model 2 Architecture (Model-View-Controller) As you might expect, the Model 2 architecture builds on the Model 1 architecture you've just seen, and it overcomes many of the problems identified earlier. The Model 2 architecture is a server-side implementation of the popular Model-View Controller (MVC) design pattern. This pattern enforces the separation of the way application data is modeled (hence, the model) from the way it’s presented (the view), and it also requires a separate component to handle the processing in between (the controller). Separating these responsibilities into components gives the developer a good opportunity to select the right type of companent for each based on its suitability to the task As mentioned earlier, JSP pages are best used for presenting content and aren't partieu- larly good for providing complex business processing because readability and maintainability wauld decline. Servlets, on the other hand, are particularly good components for providing business processing but arent best suited (o generating content. Most applications imple- menting the Madel 2 architecture therefore utilize a controller servlet to handle all the request processing and delegate requests to separate JSP components to provide the presentation, thereby making the best use of both technologies. Remember that the Model | architecture you saw earlier forced the controller and the view to coexist inside the same component, Which accounts for a lot of its shortcomings Asyou can see in Figure 1-4, all requests made of the web application are handled by a single controller servlet. Depending on the type of request received, the controller servlet is responsible for populating the model component with data that it has obtained, usually by interacting with the business layer. The controller then forwards the request to the JSP view CHAPTER 1 © THE ANATOMY OF A JAVASERVER PAGE = 11 component, which constructs a suitable response to the request based on the data stored in the model component. /!SPiServet Container: Data Ter Request Se ies « (Controtter) Browser -ReSpONSE f 35? (View) Figure 1-4. n a Model 2 architecture, different components handle the application processing and the presentation ofdata. There are, as always, varying versions af this architecture, such as providing multiple con- trollers to distribute the request-handling functionality actoss multiple servlets, Althaugh not recommended, it’ also possible to provide JSP-based controllers and servlet-based view com= ponents; the choice is yours! Remember that the best designs select a component based on its suitability for its job, JSP pages make poor controllers because they're designed to render content, whereas servlets are best suited to request processing and computations instead of generat Whatever components you select, you cannot fail to appreciate how much cleaner this architecture is than the Model 1 architecture; each component has a definite, well-defined role. Let's revisit some of the problems that the Madel 1 architecture faced and see how this new design helps solve some of them, content. Maintainability Many ofthe maintainability problems associated with the Model I architecture were a direct result ofimplementing a controller and view as part of the same component: the JSP page. Because all the business processing and content generation were forced together, the result ‘was messy pages that could be hard to maintain, By separating your application's logic from its presentation by using MVC components, its far easier to develop cleaner code that focuses specifically on the job at hand, resulting ultimately in a more flexible and maintainable application. Security By providing an initial single point of access for potential requests, a serviet-based controller componentis an excellent place to provide some form of authentication. Ifthe user making the request can pass the authentication mechanism (perhaps a username or password test), the controller can continue with the request as usual or alternatively forward it to an appro- priate page (perhaps a login page!) where the error can be dealt with, w CHAPTER 1 © THE ANATOMY OF A JAVASERVER PAGE Recause the controller components responsible for handling every request, security checks have to exist in anly a single place, and of course any changes to the security mecha- nism have to be made only once. By implementing your security constraints in a single place, it’s far easier to take advantage of declarative security mechanisms. Recall that the Madel 1 architecture required each page to provide similar security checks by itself, which provides a significant security hole if the developer forgets ta provide it! Extensibility One of the best points about the Model 2 architecture is that all the processing logic is central- ized. No longer does such code have to be placed ina scriptlet located deep within a JSP page. where it's so much more difficult to access, This centralization helps to provide a more component-based solution. By utilizing JavaBeans components and custam or standard actions, and enabling saftware components, to be reused and extended, you greatly reduce the chance of making a change that causes a “ripple” effect to other dependent components. JSP Fundamentals—Hands On Before you take an in-depth look at the individual components that compose a JSP page, you should have a basic idea of how ISP applications are deployed and structured inside a JSP container. Basic Deployment Although all JSP and servlet containers have their own specific deployment processes, gener- ally the basic techniques are still the same: you copy your web application (JSP pages, servlets, and static HTML} in a predefined structure into a special deployment directory specified by the container. The Java Servlet specification defines a special structure that all web applications must followso that servlet/JSP containers know exactly where to find the resources that compose the web application. Most containers allow web applications to be deployed in one of the fol- Jowing two forms: * Expanded directory format: The web application in its predefined structure is simply copied into the containers deployment directory, + Web ARchive file (WAR); The web application in its predefined structure is archived into a compressed WAR before being copied to the container's deployment directory. ‘The web-application structure defines the exact locations inside your web applications to locate deployment descriptors, HTML and JSP pages, and compiled Java classes as well as third-party Java ARChive (JAR) files that are required by your web applications. We won't explain the intricacies of the web-application structure because this will be covered in far greater detail in later chapters, For now we will explain the structure of a minimal but fully functional web application that you ean use to test the simple JSP examples you will learn about throughout this chapter. CHAPTER 1 © THE ANATOMY OF A JAVASERVER PAGE = 13. Because Tomcat & for the Apache Jakarta project is the reference implementation of the Servlet 2.5 and JSP 2.1 specifications and will therefore be featured heavily throughout t book, it makes sense to base the deployment introduction around the Tomcat 5 container; but feel free to use the container of your choice. When we refer to Tomcat 5, you can take that to mean Tomcat 5.0 or Tomcat 5.5. Both versions support the latest servlet and JSP specifications, However, Tomcat 5.5 has numerous improvements over 5.0; the potential obstacle you face is that Tomeat 5.5 requires the use of J2SE 5,0 whereas Tomcat 5.0 needs only J2SE 1.4, Ifyou can, we recommend you use Tomcat 5.5. Ifyou haven't yet done so, you should download and install Tomcat 5.0 or 5.5. Temeat can be downloaded from http: //jakarta-apache .org. The installation is automated for simplicity, and instructions for installing Tomcat can be found on the Tomcat home page. IF you are using some other web container, such as JBoss, BEA WebLogic, or the Sun Application Server, install your container according to the documentation with your container. Notice, in Figure 1-5, that Tomcat has been installed beneath the €: \Program Files\Apache Software Foundation\Toncat 5.5 directory, which will be referred to as the STOMCAT_ HOMES directory from now on. Ifyou have Tomcat installed on Mac OS X or-a Unix variant, you will havea directory structure that is similar, but appropriate for your operating system. ‘Be Edit Yew Favortes ‘Joos Hep Om OF sen 6 tales Eris 2 KO ‘Addiess (a C:\Program Fies\apache Software Foundation\ Tomcat 5.5, ~ Bo ‘sze| Type Date Modfed Fe Folier 5/26/2005 7:57 PM Fe Folder 5/26/2005 7:57 PHL Fie Folder 6/19/20089:24 PH Fle Folder 6/19/2005 8:24 om Fle Folder 5/26/2005 7:57 PH Fie Folder 5/26/2008 7:57 PM Fle Folder 5/26/2005 7:57 PH Fle Folder 3/26/2005 7:57 PM Fie Foller 5/26/2005 7:58 PM 12a Fe 10/29/2004 1:13 PM 22KB con 10/29/2004 1:14 eM 5/26/2005 7:57 PM Figure 1-5. A typical Tomcat installation has numerous subdirectories that contatn different parts of the system, As you can see, there are a fair number of subdirectories and each has a specific purpose, For example, the bin directory contains all the necessary scripts required to start the con- tainer, and the conf directory contains all the XML-based configuration files used by Tomcat. Dan't worry abaut understanding all the complex configuration files and direetory structures; this exercise is designed to get a working web application for you to test the examples you'll seelaterin the chapter,

You might also like