Movatterモバイル変換


[0]ホーム

URL:


Document Information

Preface

Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

4.  Java Servlet Technology

What Is a Servlet?

The Example Servlets

Troubleshooting Duke's Bookstore Database Problems

Servlet Life Cycle

Handling Servlet Life-Cycle Events

Defining the Listener Class

Specifying Event Listener Classes

Handling Servlet Errors

Sharing Information

Using Scope Objects

Controlling Concurrent Access to Shared Resources

Accessing Databases

Initializing a Servlet

Writing Service Methods

Getting Information from Requests

Constructing Responses

Filtering Requests and Responses

Programming Filters

Programming Customized Requests and Responses

Specifying Filter Mappings

Invoking Other Web Resources

Including Other Resources in the Response

Transferring Control to Another Web Component

Accessing the Web Context

Maintaining Client State

Accessing a Session

Associating Objects with a Session

Notifying Objects That Are Associated with a Session

Session Management

Session Tracking

Finalizing a Servlet

Tracking Service Requests

Notifying Methods to Shut Down

Creating Polite Long-Running Methods

Further Information about Java Servlet Technology

5.  JavaServer Pages Technology

6.  JavaServer Pages Documents

7.  JavaServer Pages Standard Tag Library

8.  Custom Tags in JSP Pages

9.  Scripting in JSP Pages

10.  JavaServer Faces Technology

11.  Using JavaServer Faces Technology in JSP Pages

12.  Developing with JavaServer Faces Technology

13.  Creating Custom UI Components

14.  Configuring JavaServer Faces Applications

15.  Internationalizing and Localizing Web Applications

Part III Web Services

16.  Building Web Services with JAX-WS

17.  Binding between XML Schema and Java Classes

18.  Streaming API for XML

19.  SOAP with Attachments API for Java

Part IV Enterprise Beans

20.  Enterprise Beans

21.  Getting Started with Enterprise Beans

22.  Session Bean Examples

23.  A Message-Driven Bean Example

Part V Persistence

24.  Introduction to the Java Persistence API

25.  Persistence in the Web Tier

26.  Persistence in the EJB Tier

27.  The Java Persistence Query Language

Part VI Services

28.  Introduction to Security in the Java EE Platform

29.  Securing Java EE Applications

30.  Securing Web Applications

31.  The Java Message Service API

32.  Java EE Examples Using the JMS API

33.  Transactions

34.  Resource Connections

35.  Connector Architecture

Part VII Case Studies

36.  The Coffee Break Application

37.  The Duke's Bank Application

Part VIII Appendixes

A.  Java Encoding Schemes

B.  About the Authors

Index

 

The Java EE 5 Tutorial

Java Coffee Cup logo
PreviousContentsNext

Servlet Life Cycle

The life cycle of a servlet is controlled by the container inwhich the servlet has been deployed. When a request is mapped to aservlet, the container performs the following steps.

  1. If an instance of the servlet does not exist, the web container

    1. Loads the servlet class.

    2. Creates an instance of the servlet class.

    3. Initializes the servlet instance by calling theinit method. Initialization is covered inInitializing a Servlet.

  2. Invokes theservice method, passing request and response objects. Service methods are discussed inWriting Service Methods.

If the container needs to remove the servlet, it finalizes the servlet bycalling the servlet’sdestroy method. Finalization is discussed inFinalizing a Servlet.

Handling Servlet Life-Cycle Events

You can monitor and react to events in a servlet’s life cycle bydefining listener objects whose methods get invoked when life-cycle events occur. To usethese listener objects you must define and specify the listener class.

Defining the Listener Class

You define a listener class as an implementation of a listener interface.Table 4-2lists the events that can be monitored and the corresponding interface that mustbe implemented. When a listener method is invoked, it is passed an eventthat contains information appropriate to the event. For example, the methods in theHttpSessionListener interface are passed anHttpSessionEvent, which contains anHttpSession.

Table 4-2 Servlet Life-Cycle Events

Object

Event

Listener Interface and EventClass

Web context (seeAccessing the Web Context)

Initialization and destruction

javax.servlet.ServletContextListener and

ServletContextEvent

Attribute added, removed, or replaced

javax.servlet.ServletContextAttributeListener and

ServletContextAttributeEvent

Session(SeeMaintaining Client State)

Creation, invalidation, activation, passivation, and timeout

javax.servlet.http.HttpSessionListener,javax.servlet.http.HttpSessionActivationListener, and

HttpSessionEvent

Attribute added, removed, orreplaced

javax.servlet.http.HttpSessionAttributeListener and

HttpSessionBindingEvent

Request

A servlet request has started being processed by web components

javax.servlet.ServletRequestListener and

ServletRequestEvent

Attributeadded, removed, or replaced

javax.servlet.ServletRequestAttributeListener and

ServletRequestAttributeEvent

Thetut-install/javaeetutorial5/examples/web/bookstore1/src/java/com/sun/bookstore1/listeners/ContextListener class creates and removes the database access and counter objects usedin the Duke’s Bookstore application. The methods retrieve the web context object fromServletContextEvent and then store (and remove) the objects as servlet context attributes.

import database.BookDBAO;import javax.servlet.*;import util.Counter;import javax.ejb.*;import javax.persistence.*;public final class ContextListener    implements ServletContextListener {    private ServletContext context = null;    @PersistenceUnit    EntityManagerFactory emf;    public void contextInitialized(ServletContextEvent event) {        context = event.getServletContext();        try {            BookDBAO bookDB = new BookDBAO(emf);            context.setAttribute("bookDB", bookDB);        } catch (Exception ex) {            System.out.println(                "Couldn’t create database: " + ex.getMessage());        }        Counter counter = new Counter();        context.setAttribute("hitCounter", counter);        counter = new Counter();        context.setAttribute("orderCounter", counter);    }    public void contextDestroyed(ServletContextEvent event) {        context = event.getServletContext();        BookDBAO bookDB = context.getAttribute("bookDB");        bookDB.remove();        context.removeAttribute("bookDB");        context.removeAttribute("hitCounter");        context.removeAttribute("orderCounter");    }}
Specifying Event Listener Classes

You specify an event listener class using thelistener element of the deploymentdescriptor. ReviewThe Example Servlets for information on how to specify theContextListener listener class.

You can specify an event listener using the deployment descriptor editor of NetBeansIDE by doing the following:

  1. Expand your application’s project node.

  2. Expand the project’s Web Pages and WEB-INF nodes.

  3. Double-clickweb.xml.

  4. Click General at the top of theweb.xml editor.

  5. Expand the Web Application Listeners node.

  6. Click Add.

  7. In the Add Listener dialog, click Browse to locate the listener class.

  8. Click OK.

Handling Servlet Errors

Any number of exceptions can occur when a servlet executes. When an exceptionoccurs, the web container generates a default page containing the message

A Servlet Exception Has Occurred

But you can also specify that the container should return a specific errorpage for a given exception. Review the deployment descriptor file included with theexample to learn how to map the exceptionsexception.BookNotFound,exception.BooksNotFound, andexception.OrderExceptionreturned by the Duke’s Bookstore application toerrorpage.html.

SeeMapping Errors to Error Screens for instructions on how to specify error pages using NetBeans IDE.

PreviousContentsNext

Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices


[8]ページ先頭

©2009-2025 Movatter.jp