You are previewing Core Servlets and JavaServer Pages™: Volume 1: Core Technologies, 2nd Edition.
O'Reilly logo
Core Servlets and JavaServer Pages™: Volume 1: Core Technologies, 2nd Edition

Book Description

The J2EE(TM) Platform has become the technology of choice for developing professional e-commerce applications, interactive Web sites, and Web-enabled applications and services. Servlet and JSP(TM) technology is the foundation of this platform: it provides the link between Web clients and server-side applications. In this 2nd edition of the worldwide bestseller, the authors show you how to apply the latest servlet and JSP capabilities. Unlike other books that treat servlet or JSP technology in isolation, Core Servlets and JavaServer Pages provides a unified treatment, showing you when servlet technology is best, when the JSP approach is preferred, and when (and how) servlets and JSP should work together.

Part I provides exhaustive coverage of the servlet 2.4 specification. It starts with server configuration, basic syntax, the servlet life cycle, and use of form data. It moves on to applying HTTP 1.1, cookies, and session tracking. Advanced topics include compressing Web content, incrementally updating results, dynamically generating images, and creating shopping carts.

Part II gives an in-depth guide to JSP 2.0. It covers both the "classic" JSP scripting elements and the new JSP 2.0 expression language. It shows how to control the content type, designate error pages, include files, and integrate JavaBeans components. Advanced topics include sharing beans, generating Excel spreadsheets, and dealing with concurrency.

Part III covers two key supporting technologies: HTML forms and database access with JDBC(TM). It explains every standard HTML input element and shows how to use appropriate JDBC drivers, perform database queries, process results, and perform updates. Advanced topics include parameterized queries, stored procedures, and transaction control.

Design strategies include ways to integrate servlet and JSP technology, best practices for invoking Java code from JSP pages, plans for dealing with missing and malformed data, and application of the MVC architecture.

Handy guides walk you through use of three popular servlet and JSP engines (Apache Tomcat, Macromedia JRun, and Caucho Resin) and some of the most widely used database systems (MySQL, Oracle9i, Microsoft Access).

Volume 2 of this book covers advanced topics: filters, custom tag libraries, database connection pooling, Web application security, the JSP Standard Tag Library (JSTL), Apache Struts, JavaServer Faces (JSF), JAXB, and more.

  • The same clear step-by-step explanations that made the first edition so popular

  • Completely updated for the latest standards: servlets 2.4 and JSP 2.0

  • Hundreds of completely portable, fully documented,industrial-strength examples

Detailed treatment of Apache Tomcat, Macromedia JRun, and Caucho Resin Online access to all source code, available free for unrestricted use at the author's www.coreservlets.com web site.

Table of Contents

  1. Copyright
  2. Acknowledgments
    1. About the Authors
  3. Introduction
    1. Who Should Read This Book
    2. Volume 2
    3. Distinctive Features
      1. Integrated Coverage of Servlets and JSP
      2. Real Code
      3. Step-by-Step Instructions
      4. Server Configuration and Usage Details
      5. Design Strategies
    4. How This Book Is Organized
      1. Part I: Servlet Technology
      2. Part II: JSP Technology
      3. Part III: Supporting Technologies
    5. Conventions
    6. About the Web Site
      1. About the Training Courses
  4. 1. An Overview of Servlet and JSP Technology
    1. 1.1. A Servlet's Job
    2. 1.2. Why Build Web Pages Dynamically?
    3. 1.3. A Quick Peek at Servlet Code
    4. 1.4. The Advantages of Servlets Over “Traditional” CGI
      1. Efficient
      2. Convenient
      3. Powerful
      4. Portable
      5. Inexpensive
      6. Secure
      7. Mainstream
    5. 1.5. The Role of JSP
  5. I. Servlet Technology
    1. 2. Server Setup and Configuration
      1. 2.1. Download and Install the Java Software Development Kit (SDK)
      2. 2.2. Download a Server for Your Desktop
      3. 2.3. Configure the Server
      4. 2.4. Configuring Apache Tomcat
        1. Setting the JAVA_HOME Variable
        2. Specifying the Server Port
        3. Enabling Servlet Reloading
        4. Enabling the ROOT Context
        5. Turning on the Invoker Servlet
        6. Increasing DOS Memory Limits
        7. Setting CATALINA_HOME
        8. Testing the Basic Server Setup
      5. 2.5. Configuring Macromedia JRun
        1. The JRun Serial Number
        2. JRun User Restrictions
        3. The Java Installation Location
        4. The Server Installation Location
        5. The Administrator Username and Password
        6. The Autostart Capability
        7. The Server Port
        8. Testing the Basic Server Setup
      6. 2.6. Configuring Caucho Resin
        1. Setting the JAVA_HOME Variable
        2. Specifying the Resin Port
        3. Testing the Basic Server Setup
      7. 2.7. Set Up Your Development Environment
        1. Creating a Development Directory
        2. Setting Your CLASSPATH
        3. Making Shortcuts to Start and Stop the Server
        4. Bookmarking or Installing the Servlet and JSP API Documentation
      8. 2.8. Test Your Setup
        1. Verifying Your SDK Installation
        2. Checking Your Basic Server Configuration
        3. Compiling and Deploying Some Simple Servlets
          1. Test 1: A Servlet That Does Not Use Packages
          2. Test 2: A Servlet That Uses Packages
          3. Test 3: A Servlet That Uses Packages and Utilities
      9. 2.9. Establish a Simplified Deployment Method
        1. Copying to a Shortcut or Symbolic Link
        2. Using the -d Option of javac
        3. Letting Your IDE Take Care of Deployment
        4. Using ant or a Similar Tool
      10. 2.10. Deployment Directories for Default Web Application: Summary
        1. Tomcat
          1. HTML and JSP Pages
          2. Individual Servlet and Utility Class Files
          3. Servlet and Utility Class Files Bundled in JAR Files
        2. JRun
          1. HTML and JSP Pages
          2. Individual Servlet and Utility Class Files
          3. Servlet and Utility Class Files Bundled in JAR Files
        3. Resin
          1. HTML and JSP Pages
          2. Individual Servlet and Utility Class Files
          3. Servlet and Utility Class Files Bundled in JAR Files
      11. 2.11. Web Applications: A Preview
        1. Making a Web Application Directory
        2. Updating Your CLASSPATH
        3. Registering the Web Application with the Server
          1. WAR Files
        4. Using the URL Prefix
        5. Assigning Custom URLs to Your Servlets
          1. Locating the Deployment Descriptor
          2. Defining the Base Format
          3. Naming Servlets
          4. Giving URLs
          5. Reading the Deployment Descriptor
          6. Example
    2. 3. Servlet Basics
      1. 3.1. Basic Servlet Structure
      2. 3.2. A Servlet That Generates Plain Text
      3. 3.3. A Servlet That Generates HTML
      4. 3.4. Servlet Packaging
      5. 3.5. Simple HTML-Building Utilities
      6. 3.6. The Servlet Life Cycle
        1. The service Method
        2. The doGet, doPost, and doXxx Methods
        3. The init Method
          1. General Initializations
          2. Initializations Controlled by Initialization Parameters
        4. The destroy Method
      7. 3.7. The SingleThreadModel Interface
      8. 3.8. Servlet Debugging
    3. 4. Handling the Client Request: Form Data
      1. 4.1. The Role of Form Data
      2. 4.2. Reading Form Data from Servlets
        1. Reading Single Values: getParameter
        2. Reading Multiple Values: getParameterValues
        3. Looking Up Parameter Names: getParameterNames and getParameterMap
        4. Reading Raw Form Data and Parsing Uploaded Files: getReader or getInputStream
        5. Reading Input in Multiple Character Sets: setCharacterEncoding
      3. 4.3. Example: Reading Three Parameters
      4. 4.4. Example: Reading All Parameters
      5. 4.5. Using Default Values When Parameters Are Missing or Malformed
      6. 4.6. Filtering Strings for HTML-Specific Characters
        1. Code for Filtering
        2. Example: A Servlet That Displays Code Snippets
      7. 4.7. Automatically Populating Java Objects from Request Parameters: Form Beans
        1. Putting BeanUtilities to Work
        2. Obtaining and Installing the Jakarta Commons Packages
      8. 4.8. Redisplaying the Input Form When Parameters Are Missing or Malformed
        1. Redisplay Options
        2. A Servlet That Processes Auction Bids
    4. 5. Handling the Client Request: HTTP Request Headers
      1. 5.1. Reading Request Headers
      2. 5.2. Making a Table of All Request Headers
      3. 5.3. Understanding HTTP 1.1 Request Headers
      4. 5.4. Sending Compressed Web Pages
      5. 5.5. Differentiating Among Different Browser Types
      6. 5.6. Changing the Page According to How the User Got There
      7. 5.7. Accessing the Standard CGI Variables
        1. Servlet Equivalent of CGI Variables
        2. A Servlet That Shows the CGI Variables
    5. 6. Generating the Server Response: HTTP Status Codes
      1. 6.1. Specifying Status Codes
        1. Setting Arbitrary Status Codes: setStatus
        2. Setting 302 and 404 Status Codes: sendRedirect and sendError
      2. 6.2. HTTP 1.1 Status Codes
      3. 6.3. A Servlet That Redirects Users to Browser-Specific Pages
      4. 6.4. A Front End to Various Search Engines
    6. 7. Generating the Server Response: HTTP Response Headers
      1. 7.1. Setting Response Headers from Servlets
      2. 7.2. Understanding HTTP 1.1 Response Headers
      3. 7.3. Building Excel Spreadsheets
      4. 7.4. Persistent Servlet State and Auto-Reloading Pages
        1. Finding Prime Numbers for Use with Public Key Cryptography
      5. 7.5. Using Servlets to Generate JPEG Images
    7. 8. Handling Cookies
      1. 8.1. Benefits of Cookies
        1. Identifying a User During an E-commerce Session
        2. Remembering Usernames and Passwords
        3. Customizing Sites
        4. Focusing Advertising
      2. 8.2. Some Problems with Cookies
      3. 8.3. Deleting Cookies
      4. 8.4. Sending and Receiving Cookies
        1. Sending Cookies to the Client
          1. Creating a Cookie Object
          2. Setting the Maximum Age
          3. Placing the Cookie in the Response Headers
        2. Reading Cookies from the Client
          1. Call request.getCookies
          2. Loop Down the Cookie Array
      5. 8.5. Using Cookies to Detect First-Time Visitors
      6. 8.6. Using Cookie Attributes
      7. 8.7. Differentiating Session Cookies from Persistent Cookies
      8. 8.8. Basic Cookie Utilities
        1. Finding Cookies with Specified Names
        2. Creating Long-Lived Cookies
      9. 8.9. Putting the Cookie Utilities into Practice
      10. 8.10. Modifying Cookie Values: Tracking User Access Counts
      11. 8.11. Using Cookies to Remember User Preferences
    8. 9. Session Tracking
      1. 9.1. The Need for Session Tracking
        1. Cookies
        2. URL Rewriting
        3. Hidden Form Fields
        4. Session Tracking in Servlets
      2. 9.2. Session Tracking Basics
        1. Accessing the Session Object Associated with the Current Request
        2. Looking Up Information Associated with a Session
        3. Associating Information with a Session
        4. Discarding Session Data
      3. 9.3. The Session-Tracking API
      4. 9.4. Browser Sessions vs. Server Sessions
      5. 9.5. Encoding URLs Sent to the Client
      6. 9.6. A Servlet That Shows Per-Client Access Counts
      7. 9.7. Accumulating a List of User Data
      8. 9.8. An Online Store with a Shopping Cart and Session Tracking
        1. Creating the Front End
        2. Handling the Orders
        3. Behind the Scenes: Implementing the Shopping Cart and Catalog Items
  6. II. JSP Technology
    1. 10. Overview of JSP Technology
      1. 10.1. The Need for JSP
      2. 10.2. Benefits of JSP
      3. 10.3. Advantages of JSP Over Competing Technologies
        1. Versus .NET and Active Server Pages (ASP)
        2. Versus PHP
        3. Versus Pure Servlets
        4. Versus JavaScript
        5. Versus WebMacro or Velocity
      4. 10.4. Misconceptions About JSP
        1. Forgetting JSP Is Server-Side Technology
        2. Confusing Translation Time with Request Time
        3. Thinking JSP Alone Is Sufficient
        4. Thinking Servlets Alone Are Sufficient
      5. 10.5. Installation of JSP Pages
        1. JSP Directories for Tomcat (Default Web Application)
        2. JSP Directories for JRun (Default Web Application)
        3. JSP Directories for Resin (Default Web Application)
      6. 10.6. Basic Syntax
        1. HTML Text
        2. HTML Comments
        3. Template Text
        4. JSP Comment
        5. JSP Expression
        6. JSP Scriptlet
        7. JSP Declaration
        8. JSP Directive
        9. JSP Action
        10. JSP Expression Language Element
        11. Custom Tag (Custom Action)
        12. Escaped Template Text
    2. 11. Invoking Java Code with JSP Scripting Elements
      1. 11.1. Creating Template Text
      2. 11.2. Invoking Java Code from JSP
        1. Types of JSP Scripting Elements
      3. 11.3. Limiting the Amount of Java Code in JSP Pages
        1. The Importance of Using Packages
      4. 11.4. Using JSP Expressions
        1. Predefined Variables
        2. JSP/Servlet Correspondence
        3. XML Syntax for Expressions
      5. 11.5. Example: JSP Expressions
      6. 11.6. Comparing Servlets to JSP Pages
      7. 11.7. Writing Scriptlets
        1. JSP/Servlet Correspondence
        2. XML Syntax for Scriptlets
      8. 11.8. Scriptlet Example
      9. 11.9. Using Scriptlets to Make Parts of the JSP Page Conditional
      10. 11.10. Using Declarations
        1. JSP/Servlet Correspondence
        2. XML Syntax for Declarations
      11. 11.11. Declaration Example
      12. 11.12. Using Predefined Variables
      13. 11.13. Comparing JSP Expressions, Scriptlets, and Declarations
        1. Example 1: JSP Expressions
        2. Example 2: JSP Scriptlets
        3. Example 3: JSP Declarations
    3. 12. Controlling the Structure of Generated Servlets: The JSP page Directive
      1. 12.1. The import Attribute
      2. 12.2. The contentType and pageEncoding Attributes
        1. Generating Excel Spreadsheets
      3. 12.3. Conditionally Generating Excel Spreadsheets
      4. 12.4. The session Attribute
      5. 12.5. The isELIgnored Attribute
      6. 12.6. The buffer and autoFlush Attributes
      7. 12.7. The info Attribute
      8. 12.8. The errorPage and isErrorPage Attributes
      9. 12.9. The isThreadSafe Attribute
      10. 12.10. The extends Attribute
      11. 12.11. The language Attribute
      12. 12.12. XML Syntax for Directives
    4. 13. Including Files and Applets in JSP Pages
      1. 13.1. Including Pages at Request Time: The jsp:include Action
        1. The page Attribute: Specifying the Included Page
        2. XML Syntax and jsp:include
        3. The flush Attribute
        4. A News Headline Page
        5. The jsp:param Element: Augmenting Request Parameters
      2. 13.2. Including Files at Page Translation Time: The include Directive
        1. Maintenance Problems with the include Directive
        2. Additional Power from the include Directive
        3. Updating the Main Page
        4. XML Syntax for the include Directive
        5. Example: Reusing Footers
      3. 13.3. Forwarding Requests with jsp:forward
      4. 13.4. Including Applets for the Java Plug-In
        1. The jsp:plugin Element
        2. The jsp:param and jsp:params Elements
        3. The jsp:fallback Element
        4. A jsp:plugin Example
    5. 14. Using JavaBeans Components in JSP Documents
      1. 14.1. Why Use Beans?
      2. 14.2. What Are Beans?
      3. 14.3. Using Beans: Basic Tasks
        1. Building Beans: jsp:useBean
        2. Installing Bean Classes
        3. Using jsp:useBean Options: scope, beanName, and type
        4. Accessing Bean Properties: jsp:getProperty
        5. Setting Simple Bean Properties: jsp:setProperty
      4. 14.4. Example: StringBean
      5. 14.5. Setting Bean Properties: Advanced Techniques
        1. Associating Individual Properties with Input Parameters
        2. Associating All Properties with Request Parameters
      6. 14.6. Sharing Beans
        1. Creating Beans Conditionally
      7. 14.7. Sharing Beans in Four Different Ways: An Example
        1. Building the Bean and the Bean Tester
        2. Using scope="page"—No Sharing
        3. Using Request-Based Sharing
        4. Using Session-Based Sharing
        5. Using ServletContext-Based Sharing
    6. 15. Integrating Servlets and JSP: The Model View Controller (MVC) Architecture
      1. 15.1. Understanding the Need for MVC
        1. MVC Frameworks
        2. Architecture or Approach?
      2. 15.2. Implementing MVC with RequestDispatcher
        1. Defining Beans to Represent the Data
        2. Writing Servlets to Handle Requests
        3. Populating the Beans
        4. Storing the Results
        5. Forwarding Requests to JSP Pages
          1. Forwarding to Static Resources
          2. Redirecting Instead of Forwarding
        6. Extracting Data from Beans
      3. 15.3. Summarizing MVC Code
        1. Request-Based Data Sharing
          1. Servlet
          2. JSP Page
        2. Session-Based Data Sharing
          1. Servlet
          2. JSP Page
        3. Application-Based Data Sharing
          1. Servlet
          2. JSP Page
      4. 15.4. Interpreting Relative URLs in the Destination Page
      5. 15.5. Applying MVC: Bank Account Balances
      6. 15.6. Comparing the Three Data-Sharing Approaches
        1. Request-Based Sharing
        2. Session-Based Sharing
        3. Application-Based Sharing
      7. 15.7. Forwarding Requests from JSP Pages
      8. 15.8. Including Pages
    7. 16. Simplifying Access to Java Code: The JSP 2.0 Expression Language
      1. 16.1. Motivating EL Usage
      2. 16.2. Invoking the Expression Language
        1. Escaping Special Characters
      3. 16.3. Preventing Expression Language Evaluation
        1. Deactivating the Expression Language in an Entire Web Application
        2. Deactivating the Expression Language in Multiple JSP Pages
        3. Deactivating the Expression Language in Individual JSP Pages
        4. Deactivating Individual Expression Language Statements
      4. 16.4. Preventing Use of Standard Scripting Elements
      5. 16.5. Accessing Scoped Variables
        1. Choosing Attribute Names
        2. An Example
      6. 16.6. Accessing Bean Properties
        1. Equivalence of Dot Notation and Array Notation
        2. An Example
      7. 16.7. Accessing Collections
        1. An Example
      8. 16.8. Referencing Implicit Objects
        1. An Example
      9. 16.9. Using Expression Language Operators
        1. Arithmetic Operators
        2. Relational Operators
        3. Logical Operators
        4. The empty Operator
        5. An Example
      10. 16.10. Evaluating Expressions Conditionally
        1. An Example
      11. 16.11. Previewing Other Expression Language Capabilities
  7. III. Supporting Technology
    1. 17. Accessing Databases with JDBC
      1. 17.1. Using JDBC in General
        1. Load the JDBC Driver
        2. Define the Connection URL
        3. Establish the Connection
        4. Create a Statement Object
        5. Execute a Query or Update
        6. Process the Results
        7. Close the Connection
      2. 17.2. Basic JDBC Examples
      3. 17.3. Simplifying Database Access with JDBC Utilities
      4. 17.4. Using Prepared Statements
      5. 17.5. Creating Callable Statements
        1. Define the Call to the Database Procedure
        2. Prepare a CallableStatement for the Procedure
        3. Register the Output Parameter Types
        4. Provide Values for the Input Parameters
        5. Execute the Stored Procedure
        6. Access the Output Parameters
        7. Example
      6. 17.6. Using Database Transactions
      7. 17.7. Mapping Data to Objects by Using ORM Frameworks
    2. 18. Configuring MS Access, MySQL, and Oracle9i
      1. 18.1. Configuring Microsoft Access for Use with JDBC
        1. Select a System DSN from the ODBC Data Source Administrator
        2. Select a Driver for the New System DSN
        3. Select a Data Source
        4. Select OK to Accept the New DSN
      2. 18.2. Installing and Configuring MySQL
        1. Download and Install MySQL
        2. Create a Database
        3. Create a User
        4. Install the JDBC Driver
      3. 18.3. Installing and Configuring Oracle9i Database
        1. Download and Install Oracle9i
          1. Steps to Install Oracle9i
        2. Create a Database
        3. Create a Database with the Configuration Assistant
        4. Create a Database Manually
          1. Set Up Database Directories
          2. Create an Initialization Parameter File
          3. Create a Password File
          4. Create an Oracle Service for the Database
          5. Declare the ORACLE_SID Value
          6. Connect to the Oracle Service as SYSDBA
          7. Start the Oracle Instance
          8. Create the Database
          9. Create a User Tablespace
          10. Run Scripts to Build Data Dictionary Views
        5. Create a User
        6. Install the JDBC Driver
      4. 18.4. Testing Your Database Through a JDBC Connection
      5. 18.5. Setting Up the music Table
        1. Using CreateMusicTable.java to Create the music Table
        2. Using create_music_table.sql to Create the music Table
    3. 19. Creating and Processing HTML Forms
      1. Default Web Application: Tomcat
      2. Default Web Application: JRun
      3. Default Web Application: Resin
      4. 19.1. How HTML Forms Transmit Data
      5. 19.2. The FORM Element
      6. 19.3. Text Controls
        1. Textfields
        2. Password Fields
        3. Text Areas
      7. 19.4. Push Buttons
        1. Submit Buttons
        2. Reset Buttons
        3. JavaScript Buttons
      8. 19.5. Check Boxes and Radio Buttons
        1. Check Boxes
        2. Radio Buttons
      9. 19.6. Combo Boxes and List Boxes
      10. 19.7. File Upload Controls
      11. 19.8. Server-Side Image Maps
        1. IMAGE—Standard Server-Side Image Maps
        2. ISMAP—Alternative Server-Side Image Maps
      12. 19.9. Hidden Fields
      13. 19.10. Groups of Controls
      14. 19.11. Tab Order Control
      15. 19.12. A Debugging Web Server
        1. EchoServer
    4. Server Organization and Structure
      1. Tomcat
        1. Downloading the Software
        2. Bookmarking the Servlet and JSP APIs
          1. Tomcat 4
          2. Tomcat 5
        3. Configuring the Server
        4. Setting Up Your Development Environment
        5. Using the Default Web Application
          1. Packageless Servlets
          2. Packaged Servlets
          3. Packaged Beans and Utility Classes
          4. JAR Files
          5. HTML and JSP Pages (Not In Subdirectories)
          6. HTML and JSP Pages (In Subdirectories)
        6. Using Custom Web Applications
          1. Packageless Servlets
          2. Packaged Servlets
          3. Packaged Beans and Utility Classes
          4. JAR Files
          5. HTML and JSP Pages (Not In Subdirectories)
          6. HTML and JSP Pages (In Subdirectories)
        7. Viewing Autogenerated Code for JSP Pages
      2. JRun
        1. Downloading the Software
        2. Bookmarking the Servlet and JSP APIs
          1. Servlets 2.3 and JSP 1.2
          2. Servlets 2.4 and JSP 2.0
        3. Configuring the Server
        4. Setting Up Your Development Environment
        5. Using the Default Web Application
          1. Packageless Servlets
          2. Packaged Servlets
          3. Packaged Beans and Utility Classes
          4. JAR Files
          5. HTML and JSP Pages (Not In Subdirectories)
          6. HTML and JSP Pages (In Subdirectories)
        6. Using Custom Web Applications
          1. Packageless Servlets
          2. Packaged Servlets
          3. Packaged Beans and Utility Classes
          4. JAR Files
          5. HTML and JSP Pages (Not In Subdirectories)
          6. HTML and JSP Pages (In Subdirectories)
        7. Viewing Autogenerated Code for JSP Pages
      3. Resin
        1. Downloading the Software
        2. Bookmarking the Servlet and JSP APIs
          1. Servlets 2.3 and JSP 1.2
          2. Servlets 2.4 and JSP 2.0
        3. Configuring the Server
        4. Setting Up Your Development Environment
        5. Using the Default Web Application
          1. Packageless Servlets
          2. Packaged Servlets
          3. Packaged Beans and Utility Classes
          4. JAR Files
          5. HTML and JSP Pages (Not In Subdirectories)
          6. HTML and JSP Pages (In Subdirectories)
        6. Using Custom Web Applications
          1. Packageless Servlets
          2. Packaged Servlets
          3. Packaged Beans and Utility Classes
          4. JAR Files
          5. HTML and JSP Pages (Not In Subdirectories)
          6. HTML and JSP Pages (In Subdirectories)
        7. Viewing Autogenerated Code for JSP Pages