1. Trang chủ
  2. » Công Nghệ Thông Tin

The j2eetm tutorial - phần 5 doc

35 246 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Cấu trúc

  • Preface

    • Who Should Use This Tutorial

    • About the Examples

      • Prerequisites for the Examples

      • Where to Find the Examples

      • How to Build and Run the Examples

    • Related Information

    • How to Print This Tutorial

    • Typographical Conventions

    • Acknowledgments

  • Overview

    • Distributed Multitiered Applications

      • J2EE Application Components

      • Client Components

        • Application Clients

        • Web Browsers

        • Applets

        • JavaBeans™ Component Architecture

        • J2EE Server Communications

      • Thin Clients

      • Web Components

      • Business Components

      • Enterprise Information System Tier

    • J2EE Architecture

      • Containers and Services

      • Container Types

    • Packaging

    • Development Roles

      • J2EE Product Provider

      • Tool Provider

      • Application Component Provider

        • Enterprise Bean Creation

        • Web Component Creation

        • J2EE Application Client Creation

      • Application Assembler

      • Application Deployer and Administrator

    • Reference Implementation Software

      • Web Server

      • Database Access

      • J2EE APIs

        • Enterprise JavaBeans Technology 2.0

        • JDBC™ 2.0 API

        • Java Servlet Technology 2.3

        • JavaServer Pages (JSP) Technology 1.2

        • Java Message Service (JMS) 1.0

        • Java Transaction API (JTA) 1.0

        • JavaMail™ Technology 1.2

        • JavaBeans Activation Framework 1.0

        • Java API for XML (JAXP) 1.1

        • J2EE Connector API 1.0

        • Java Authentication and Authorization Service (JAAS) 1.0

      • Tools

        • Application Deployment Tool

        • Scripts

  • Getting Started

    • Setting Up

      • Getting the Example Code

      • Building the Example

      • Checking the Environment Variables

      • Starting the J2EE™ Server

      • Starting the deploytool

    • Creating the J2EE™ Application

    • Creating the Enterprise Bean

      • Coding the Enterprise Bean

        • Coding the Remote Interface

        • Coding the Home Interface

        • Coding the Enterprise Bean Class

      • Compiling the Source Files

      • Packaging the Enterprise Bean

    • Creating the J2EE™ Application Client

      • Coding the J2EE Application Client

        • Locating the Home Interface

        • Creating an Enterprise Bean Instance

        • Invoking a Business Method

        • ConverterClient Source Code

      • Compiling the Application Client

      • Packaging the J2EE Application Client

      • Specifying the Application Client’s Enterprise Bean Reference

    • Creating the Web Client

      • Coding the Web Client

      • Compiling the Web Client

      • Packaging the Web Client

      • Specifying the Web Client’s Enterprise Bean Reference

    • Specifying the JNDI Name

    • Deploying the J2EE™ Application

    • Running the J2EE™ Application Client

    • Running the Web Client

    • Modifying the J2EE™ Application

      • Modifying a Class File

      • Adding a File

      • Modifying the Web Client

      • Modifying a Deployment Setting

    • Common Problems and Their Solutions

      • Cannot Start the J2EE Server

        • Naming and Directory Service Port Conflict

        • Web Service Port Conflict

      • Compilation Errors

        • Ant Cannot Locate the Build File

        • The Compiler Cannot Resolve Symbols

      • J2EE Application Client Runtime Errors

        • The Client Cannot Find ConverterApp.ear

        • The Client Cannot Find the ConverterClient Component

        • The Login Failed

        • The J2EE Application Has Not Been Deployed

        • The JNDI Name is Incorrect

      • Web Client Runtime Errors

        • The Web Context in the URL is Incorrect

        • The J2EE Application Has Not Been Deployed

        • The JNDI Name is Incorrect

      • Deployment Errors

  • Session Beans

    • A Session Bean Example

      • Session Bean Class

        • The SessionBean Interface

        • The ejbCreate Methods

        • Business Methods

        • Home Interface

        • Remote Interface

      • Helper Classes

    • State Management Modes

      • Stateful Session Beans

      • Stateless Session Beans

      • Choosing Between Stateful and Stateless Session Beans

    • The Life Cycle of a Session Bean

      • The Stateful Session Bean Life Cycle

      • The Stateless Session Bean Life Cycle

    • Other Enterprise Bean Features

      • Accessing Environment Entries

      • Comparing Enterprise Beans

      • Passing an Enterprise Bean’s Object Reference

  • Entity Beans

    • Characteristics of Entity Beans

      • Persistence

        • Bean-Managed Persistence

        • Container-Managed Persistence

      • Shared Access

      • Primary Key

    • A Bean-Managed Persistence Example

      • Entity Bean Class

      • The EntityBean Interface

        • The ejbCreate Method

        • The ejbPostCreate Method

        • The ejbRemove Method

        • The ejbLoad and ejbStore Methods

        • The Finder Methods

        • The Business Methods

        • Database Calls

      • Home Interface

      • Remote Interface

      • Tips for Running the AccountEJB Example

        • Setting Up the Database

        • Running the New Enterprise Bean Wizard

        • Deploying the J2EE Application

        • Running the J2EE Application

    • Mapping Table Relationships For Bean- Managed Persistence

      • One-to-One Relationships

        • Tips for Running the StorageBinEJB Example

      • One-to-Many Relationships

        • A Helper Class for the Child Table

        • Tips for Running the OrderEJB Example:

        • An Entity Bean for the Child Table

        • Tips for Running the SalesRepEJB Example:

      • Many-to-Many Relationships

        • Tips for running the EnrollerEJB example:

    • About Container-Managed Persistence

    • A Container-Managed Persistence Example

    • Primary Key Class

      • Creating a Primary Key Class

      • Class Requirements

      • Bean-Managed Persistence and the Primary Key Class

      • Container-Managed Persistence and the Primary Key Class

      • Getting the Primary Key

    • Handling Exceptions

    • The Life Cycle of an Entity Bean

  • Web Components

    • Web Component Life Cycle

    • Packaging Web Components

      • Creating a WAR

      • Adding a WAR to a J2EE Application

      • Adding a Web Component to a WAR

    • Configuring Web Components

      • Application-Level Configuration

        • Context Root

      • WAR-Level Configuration

        • Context Parameters

        • References to Environment Entries, Enterprise Beans, Resource Environment Entries, or Resources

        • Event Listeners

        • Error Mapping

        • Filter Mapping

      • Component-Level Configuration

        • Initialization Parameters

        • Specifying an Alias Path

    • Deploying Web Components

    • Executing Web Components

    • Updating Web Components

  • Java Servlet Technology

    • What is a Servlet?

    • The Example Servlets

      • Troubleshooting

    • Servlet Life Cycle

      • Monitoring Servlet Life Cycle Events

        • Defining The Listener Class

        • Specifying Event Listener Classes

      • Handling Errors

    • Sharing Information

      • Scope Objects

      • Controlling Concurrent Access to Shared Resources

    • Initializing a Servlet

    • Writing Service Methods

      • Getting Information From Requests

      • Constructing Responses

    • Filtering Requests and Responses

      • Defining the Filter Class

      • Specifying Filter Mappings

    • Invoking Other Web Resources

      • Including the Content of Another Resource in the Response

      • Transferring a Control to Another Web Component

    • Accessing the Web Context

    • Maintaining Client State

      • Accessing a Session

      • Associating Attributes with a Session

        • Notifying Objects That Are Added To a Session

      • Session Management

      • Session Tracking

    • Finalizing a Servlet

      • Tracking Service Requests

      • Providing a Clean Shutdown

      • Creating Polite Long-Running Methods

  • JavaServer Pages™ Technology

    • What is a JSP Page?

    • The Example JSP Pages

    • The Life Cycle of a JSP Page

      • Translation and Compilation

      • Execution

        • Buffering

        • Handling Errors

    • Initializing and Finalizing a JSP Page

    • Creating Static Content

    • Creating Dynamic Content

      • Using Objects Within JSP Pages

        • Implicit Objects

        • Application-Specific Objects

        • Shared Objects

      • JSP Scripting Elements

        • Declarations

        • Scriptlets

        • Expressions

    • Including Content in a JSP Page

    • Transferring Control to Another Web Component

      • Param Element

    • Including an Applet

    • Extending the JSP Language

  • JavaBeans™ Components in JSP™ Pages

    • JavaBeans Component Design Conventions

    • Why Use a JavaBeans Component?

    • Creating and Using a JavaBeans Component

    • Setting JavaBeans Component Properties

    • Retrieving JavaBeans Component Properties

  • Custom Tags in JSP™ Pages

    • What is a Custom Tag?

    • The Example Tags

    • Using Tags

      • Declaring Tag Libraries

      • Types of Tags

        • Simple Tags

        • Tags With Attributes

        • Tags With Bodies

        • Choosing Between Passing Information as Attributes or Body

        • Tags That Define Scripting Variables

        • Cooperating Tags

    • Defining Tags

      • Tag Handlers

      • Tag Library Descriptors

        • Listener Element

        • Tag Element

      • Simple Tags

        • Tag Handlers

        • Body-content Element

      • Tags With Attributes

        • Defining Attributes in a Tag Handler

        • Attribute Element

        • Attribute Validation

      • Tags With Bodies

        • Tag Handlers

        • Body-content Element

      • Tags That Define Scripting Variables

        • Tag Handlers

        • Providing Information About the Scripting Variable

      • Cooperating Tags

    • Examples

      • An Iteration Tag

        • JSP Page

        • Tag Handler

        • Tag Extra Info Class

      • A Template Tag Library

        • JSP Page

        • Tag Handlers

    • How Is a Tag Handler Invoked?

  • Transactions

    • What is a Transaction?

    • Container-Managed Transactions

      • Transaction Attributes

        • Transaction Attribute Values

        • Required

        • RequiresNew

        • Mandatory

        • NotSupported

        • Supports

        • Never

        • Summary of Transaction Attributes

        • Setting Transaction Attributes

      • Rolling Back a Container-Managed Transaction

      • Synchronizing a Session Bean’s Instance Variables

      • Methods Not Allowed in Container-Managed Transactions

    • Bean-Managed Transactions

      • JDBC Transactions

      • JTA Transactions

      • Returning Without Committing

      • Methods Not Allowed in Bean-Managed Transactions

    • Summary of Transaction Options

    • Transaction Timeouts

    • Isolation Levels

    • Updating Multiple Databases

  • Security

    • Authentication

      • J2EE Users, Realms, and Groups

        • Managing J2EE Users and Groups

      • Authentication Mechanisms

        • Web-Tier Authentication

        • Configuring A Web Component’s Authentication Mechanism

        • Using Hybrid Authentication to Enhance Confidentiality

      • Controlling Access to J2EE Resources

        • Controlling Access to Web Resources

        • Controlling Access to Enterprise Beans

        • Unprotected Resources

      • Client Authentication

        • Auto-Registration of Users

      • Web Client Authentication

        • Data Protection

        • Developing a Custom Web Tier User Authentication Interface

      • Application Client Authentication

      • Setting Component Security Identities

        • Capturing a Security Context (Servlet)

      • Container Authentication

        • Setting Up a Server Certificate

      • Configuring EJB Target Security Requirements

      • Configuring Resource Signon (Connectors)

    • Authorization

      • Declaring Roles

      • Declaring Method Permissions

      • Declaring Role References

      • Mapping Roles to J2EE Users and Groups

      • Linking Role References to Roles

      • Configuring J2SE Security Policy Files

      • Determining the Caller Identity

      • Making Portable Access Decisions Programmatically from Components

    • Protecting Messages

    • Application Scenarios

      • J2EE Application Client

      • Web Browser Client

  • Resource Connections

    • JNDI Names and Resource References

      • Definitions

      • Specifying a Resource Reference

      • Mapping a Resource Reference to a JNDI Name

    • Database Connections for Enterprise Beans

      • Coded Connections

        • How to Connect

        • When To Connect

        • Specifying Database Users and Passwords

      • Container-Managed Connections

      • Connection Pooling

    • Mail Session Connections

      • Tips for Running the ConfirmerEJB Example

    • URL Connections

      • Tips for Running the HTMLReaderEJB Example

  • J2EE™Connector Technology

    • About Resource Adapters

      • Resource Adapter Contracts

      • Administering Resource Adapters

    • The Black Box Resource Adapters

      • Transaction Levels

      • Properties

      • Configuring JDBC™ Drivers

        • The Non-XA Black Box Adapters

        • The XA Black Box Adapters

    • Resource Adapter Tutorial

      • Setting Up

      • Deploying the Resource Adapter

      • Testing the Resource Adapter

    • Common Client Interface (CCI)

      • Overview of the CCI

      • Programming with the CCI

        • Database Stored Procedures

        • Mapping to Stored Procedure Parameters

        • Reading Database Records

        • Inserting Database Records

      • Writing a CCI Client

      • CCI Tutorial

        • Deploy the Resource Adapter

        • Set Up the Database

        • Create the J2EE Application

        • Test the Resource Adapter

  • HTTP Overview

    • HTTP Requests

    • HTTP Responses

  • J2EE™SDK Tools

    • J2EE Administration Tool

    • Cleanup Tool

    • Cloudscape Server

      • Starting and Stopping Cloudscape

      • Cloudscape Server Configuration

      • Cloudscape ij Tool

    • Deployment Tool

    • J2EE Server

    • Key Tool

    • Packager

      • EJB JAR File

        • Syntax

        • Example

      • Web Application WAR File

        • Syntax

        • Example: Creating a Simple WAR File

        • Example: Specifying Individual Content Files

        • Example: Specifying Servlets and JSP Files

      • Application Client JAR File

        • Syntax

        • Example

      • J2EE Application EAR File

        • Syntax

        • Example: Creating an EAR File

        • Example: Specifying the Runtime Deployment Descriptor

      • Resource Adapter RAR File

        • Syntax

    • Realm Tool

    • Runclient Script

    • Verifier

      • Command-Line Verifier

      • Stand-Alone GUI Verifier

  • Glossary

Nội dung

SERVLET LIFE CYCLE 141 The listeners.ContextListener class creates and removes the database helper and counter objects used in the Duke’s Bookstore application. The methods retrieve the web context object from ServletContextEvent and then store (and remove) the objects as servlet context attributes. import database.BookDB; import javax.servlet.*; import util.Counter; public final class ContextListener implements ServletContextListener { private ServletContext context = null; public void contextInitialized(ServletContextEvent event) { context = event.getServletContext(); try { BookDB bookDB = new BookDB(); context.setAttribute("bookDB", bookDB); } catch (Exception ex) { System.out.println( "Couldn't create database: " + ex.getMessage()); } Counter counter = new Counter(); context.setAttribute("hitCounter", counter); context.log("Created hitCounter" + counter.getCounter()); counter = new Counter(); context.setAttribute("orderCounter", counter); context.log("Created orderCounter" + counter.getCounter()); } public void contextDestroyed(ServletContextEvent event) { context = event.getServletContext(); BookDB bookDB = context.getAttribute( "bookDB"); bookDB.remove(); context.removeAttribute("bookDB"); context.removeAttribute("hitCounter"); context.removeAttribute("orderCounter"); } } Specifying Event Listener Classes You specify a listener class for a WAR in the deploytool Event Listeners inspector (see Event Listeners (page 126)). Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 142 JAVA SERVLET TECHNOLOGY Handling Errors Any number of exceptions can occur when a servlet is executed. The web con- tainer will generate a default page containing the message A Servlet Excep- tion Has Occurred when an exception occurs, but you can also specify that the container should return a specific error page for a given exception. You specify error pages for a WAR in the deploytool File Ref’s inspector (Error Mapping (page 126)). Sharing Information Web components, like most objects, usually work with other objects to accom- plish their tasks. There are several ways they can do this. They can use private helper objects (for example, JavaBeans components), they can share objects that are attributes of a public scope, and they can invoke other web resources. The Java Servlet technology mechanisms that allow a web component to invoke other web resources are described in Invoking Other Web Resources (page 156). Scope Objects Collaborating web components share information via objects maintained as attributes of four scope objects. These attributes are accessed with the [get|set]Attribute methods of the class representing the scope. Table 12 lists the scope objects. Table 12 Scope Objects Scope Object Class Accessible From web context javax.servlet. ServletContext Web components within a Web context. See Accessing the Web Context (page 159). session javax.servlet. http.HttpSession Web components handling a request that belongs to the session. See Maintaining Client State (page 160). request subtype of javax.servlet. ServletRequest Web components handling the request. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com SHARING INFORMATION 143 Figure 13 shows the scoped attributes maintained by the Duke’s Bookstore application. Figure 13 Duke’s Bookstore Scoped Attributes Controlling Concurrent Access to Shared Resources In a multithreaded server, it is possible for shared resources to be accessed con- currently. Besides scope object attributes, shared resources include in-memory data such as instance or class variables and external objects such as files, data- base connections, and network connections. Concurrent access can arise in sev- eral situations: • Multiple web components accessing objects stored in the web context • Multiple web components accessing objects stored in a session page javax.servlet. jsp.PageContext The JSP page that creates the object. See JavaServer Pages™ Technology (page 167). Table 12 Scope Objects (Continued) Scope Object Class Accessible From hitCounter bookDB orderCounter Web context attributes Session attribute cart BookStoreServlet ShowCartServlet ReceiptServlet CatalogServlet CashierServlet BookDetailsServlet orderFilter hitCounterFilter Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 144 JAVA SERVLET TECHNOLOGY • Multiple threads within a web component accessing instance variables. A web container will typically create a thread to handle each request. If you want to ensure that a servlet instance handles only one request at a time, a servlet can implement the SingleThreadModel interface. If a servlet implements this interface, you are guaranteed that no two threads will exe- cute concurrently in the servlet’s service method. A web container can implement this guarantee by synchronizing access to a single instance of the servlet, or by maintaining a pool of web component instances and dis- patching each new request to a free instance. This interface does not pre- vent synchronization problems that result from web components accessing shared resources such as static class variables or external objects. When resources can be accessed concurrently, they can be used in an inconsis- tent fashion. To prevent this, you must control the access using the synchroniza- tion techniques described in the Threads lesson in the Java Tutorial. The Duke’s Bookstore database helper object BookDB maintains a database connection that is referenced by an instance variable named con. Only one serv- let can use connection at a time. Since the servlets accessing this object are mul- tithreaded, access to the con variable is controlled by the synchronized methods getConnection and releaseConnection. private Connection con; private boolean conFree = true; public BookDB () throws Exception { try { InitialContext ic = new InitialContext(); DataSource ds = (DataSource) ic.lookup(dbName); con = ds.getConnection(); } catch (Exception ex) { throw new Exception( "Couldn't open connection to database: " + ex.getMessage()); } } protected synchronized Connection getConnection() { while (conFree == false) { try { wait(); } catch (InterruptedException e) { } } conFree = false; notify(); return con; Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com INITIALIZING A SERVLET 145 } protected synchronized void releaseConnection() { while (conFree == true) { try { wait(); } catch (InterruptedException e) { } } conFree = true; notify(); } Initializing a Servlet After the web container loads and instantiates the servlet class and before it delivers requests from clients, the web container initializes the servlet. You can customize this process to allow the servlet to read persistent configuration data, initialize resources, and perform any other one-time activities by overriding the init method of the Servlet interface. A servlet that cannot complete its initial- ization process should throw UnavailableException. All the servlets that access the bookstore database ( BookStoreServlet, Cata- logServlet , BookDetailsServlet, and ShowCartServlet) initialize a variable in their init method that points to the database helper object created by the web context listener: public class CatalogServlet extends HttpServlet { private BookDB bookDB; public void init() throws ServletException { bookDB = (BookDB)getServletContext(). getAttribute("bookDB"); if (bookDB == null) throw new UnavailableException("Couldn't get database."); } } Writing Service Methods The service provided by a servlet is implemented in the service method of a GenericServlet, the doMethod methods (where Method can take the value Get, Delete, Options, Post, Put, Trace)ofanHttpServlet, or any other protocol- Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 146 JAVA SERVLET TECHNOLOGY specific methods defined by a class that implements the Servlet interface. In the rest of this chapter, the term “service method” will be used for any method in a servlet class that provides a service to a client. The general pattern for a service method is to extract information from the request, access external resources, and then populate the response based on that information. For HTTP servlets, the correct procedure for populating the response is to first fill in the response headers, then retrieve an output stream from the response, and finally write any body content to the output stream. Response headers must always be set before a PrintWriter or ServletOutputStream is retrieved because the HTTP protocol expects to receive all headers before body content. The next two sections describe how to get information from requests and gener- ate responses. Getting Information From Requests A request contains data passed between a client and the servlet. All requests implement the ServletRequest interface. This interface defines methods for accessing the following information: • Parameters, which are typically used to convey information between cli- ents and servlets • Object-valued attributes, which are typically used to pass information between the servlet container and a servlet or between collaborating serv- lets • Information about the protocol used to communicate the request and the client and server involved in the request • Information relevant to localization For example, in CatalogServlet the identifier of the book that a customer wishes to purchase is included as a parameter to the request. The following code fragment illustrates how to use the getParameter method to extract the identi- fier: String bookId = request.getParameter("Add"); if (bookId != null) { BookDetails book = bookDB.getBookDetails(bookId); You can also retrieve an input stream from the request and manually parse the data. To read character data, use the BufferedReader object returned by the Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com WRITING SERVICE METHODS 147 request’s getReader method. To read binary data, use the ServletInputStream returned by getInputStream. HTTP servlets are passed an HTTP request object, HttpServletRequest, which contains the request URL, HTTP headers, query string, and so on. An HTTP request URL contains the following parts: http://[host]:[port][request path]?[query string] The request path is further composed of the following elements: • Context path: A concatenation of ’/’ with the context root of the servlet’s J2EE application. • Servlet path: The path section that corresponds to the component alias that activated this request. This path starts with a ’/’. • Path info: The part of the request path that is not part of the context path or the servlet path. Table 14 gives some examples of how the URL will be broken down if the con- text path is /catalog, and the aliases are as listed in Table 13: Table 13 Aliases Pattern Servlet /lawn/* LawnServlet /*.jsp JSPServlet Table 14 Request Path Elements Request Path Servlet Path Path Info /catalog/lawn/index.html /lawn /index.html /catalog/help/feedback.jsp /help/feedback.jsp null Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 148 JAVA SERVLET TECHNOLOGY Query strings are composed of a set of parameters and values. Individual param- eters are retrieved from a request with the getParameter method. There are two ways to generate query strings: • A query string can explicitly appear in a web page. For example, an HTML page generated by the CatalogServlet could contain the link <a href="/bookstore1/catalog?Add=101">Add To Cart</a> . Cata- logServlet extracts the parameter named Add as follows: String bookId = request.getParameter("Add"); • A query string is appended to a URL when a form with a GET HTTP method is submitted. In the Duke’s Bookstore application, Cash- ierServlet generates a form, a user name input to the form is appended to the URL that maps to ReceiptServlet, and ReceiptServlet extracts the user name using the getParameter method. Constructing Responses A response contains data passed between a server and the client. All responses implement the ServletResponse interface. This interface defines methods that allow you to: • Retrieve an output stream to use to send data to the client. To send charac- ter data, use the PrintWriter returned by the response’s getWriter method. To send binary data in a MIME body response, use the Serv- letOutputStream returned by getOutputStream. To mix binary and text data, for example, to create a multipart response, use a ServletOutput- Stream and manage the character sections manually. • Indicate the content type (for example, text/html), being returned by the response. A registry of content type names is kept by IANA at: ftp://ftp.isi.edu/in-notes/iana/assignments/media-types • Indicate whether to buffer output. By default, any content written to the output stream is immediately sent to the client. Buffering allows content to be written before anything is actually sent back to the client, thus providing the servlet with more time to set appropriate status codes and headers or forward to another web resource. • Set localization information. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com WRITING SERVICE METHODS 149 HTTP response objects, HttpServletResponse, also have fields representing HTTP headers such as • Status codes, which are used to indicate the reason of a request is not sat- isfied. • Cookies, which are used to store application-specific information at the cli- ent. Sometimes cookies are used to maintain an identifier for tracking a user’s session (see Maintaining Client State (page 160)). In Duke’s Bookstore, BookDetailsServlet generates an HTML page that dis- plays information about a book which the servlet retrieves from a database. The servlet first sets response headers: the context type of the response and the buffer size. The servlet buffers the page content because the database access can gener- ate an exception that would cause forwarding to an error page. By buffering the response, the client will not see a concatenation of part of a Duke’s Bookstore page with the error page should an error occur. The doGet method then retrieves a PrintWriter from the response. For filling in the response, the servlet first dispatches the request to BannerServ- let , which generates a common banner for all the servlets in the application. This process is discussed in Including the Content of Another Resource in the Response (page 157). Then the servlet retrieves the book identifier from a request parameter and uses the identifier to retrieve information about the book from the bookstore database. Finally the servlet generates HTML markup that describes the book information and commits the response to the client by calling the close method on the PrintWriter. public class BookDetailsServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // set headers before accessing the Writer response.setContentType("text/html"); response.setBufferSize(8192); PrintWriter out = response.getWriter(); // then write the response out.println("<html>" + "<head><title>Book Description</title></head>"); // Get the dispatcher; it gets the banner to the user RequestDispatcher dispatcher = getServletContext(). getRequestDispatcher("/banner"); if (dispatcher != null) Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 150 JAVA SERVLET TECHNOLOGY dispatcher.include(request, response); //Get the identifier of the book to display String bookId = request.getParameter("bookId"); if (bookId != null) { // and the information about the book try { BookDetails bd = bookDB.getBookDetails(bookId); //Print out the information obtained out.println("<h2>" + bd.getTitle() + "</h2>" + } catch (BookNotFoundException ex) { response.resetBuffer(); throw new ServletException(ex); } } out.println("</body></html>"); out.close(); } } BookDetailsServlet generates a page that looks like: Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... headers or data • Invoke the next entity in the filter chain If the current filter is the last filter in the chain that ends with the target web component or static resource, the next entity is the resource at the end of the chain; otherwise, it is the next filter that was configured in the WAR It invokes the next entity by calling the doFilter method on the chain object (passing in the request and response... in the response returned from a web component To include the content of another resource, invoke the include method of a RequestDispatcher: include(request, response); If the resource is static, the include method enables programmatic server-side includes If the resource is a web component, the effect of the method is to send the request to the included web component, execute the web component, and then... locale names, and conditionally insert HTML text into the output • Expressions () insert the value of the locale name into the response • The jsp:include element sends a request to another page (date.jsp) and includes the response in the response from the calling page Localized Dates... cloudscape -start 3 If you have not already created the bookstore database, run ant create-web-db 4 Start the j2ee server 5 Start deploytool 6 Create a J2EE application called bookstore2 a Select File->New Application or the New Application button b Enter bookstore2.ear in the Application File Name field c Click OK 7 Add the bookstore2 WAR to the bookstore2 application a Select File->Add to Application->Web... of a request and another component generate the response For example, you might want to partially process a request and then transfer to another component depending on the nature of the request To transfer control to another web component, you invoke the forward method of a RequestDispatcher When a request is forwarded, the request URL is set to the path of the forwarded page If the original URL is... Select the WAR 2 Select the General tab 3 Enter the time-out period in the Advanced box To ensure that an active session is not timed-out, you should periodically access the session in service methods because this resets the session’s time-to-live counter When a particular client interaction is finished, you use the session’s invalidate method to delete a session on the server side The session data is removed... instantiated After the filters have completed application-specific pro- Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com FILTERING REQUESTS AND RESPONSES cessing, they invoke doFilter on the filter chain object passed into the original doFilter method In addition to logging the value of the hit counter, HitCounterFilter also inserts the value of the counter into the response It does... increment and log the value of a counter when the entry and and receipt servlets are accessed In the doFilter method, both filters retrieve the servlet context from the filter configuration object so that they can access the counters stored as context attributes When you write the filter, you must implement the [set|get]FilterConfig methods The setFilterConfig method is called by the container when the filter is... JasperException and a mes- Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com THE LIFE CYCLE OF A JSP PAGE sage that includes the name of the JSP page’s servlet and the line where the error occurred Once the page has been translated and compiled, the JSP page’s servlet for the most part follows the servlet life cycle described in Servlet Life Cycle (page 139): 1 If an instance of the JSP page’s... are invoked in the order that filter mappings appear in the filter mapping list of a WAR You specify a filter mapping list for a WAR in the deploytool Filter Mapping inspector (see Filter Mapping (page 127)) 155 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 156 JAVA SERVLET TECHNOLOGY Table 15 contains the filter mapping list for the Duke’s Bookstore application The filters are . If the resource is a web component, the effect of the method is to send the request to the included web component, execute the web component, and then include the result of the execution in the. common banner for all the servlets in the application. This process is discussed in Including the Content of Another Resource in the Response (page 157 ). Then the servlet retrieves the book identifier. head- ers or data • Invoke the next entity in the filter chain. If the current filter is the last filter in the chain that ends with the target web component or static resource, the next entity is the

Ngày đăng: 13/08/2014, 08:21