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

Finalizing a Servlet

When a servlet container determines that a servlet should be removed from service(for example, when a container wants to reclaim memory resources or when itis being shut down), the container calls thedestroy method of theServletinterface. In this method, you release any resources the servlet is using andsave any persistent state. The followingdestroy method releases the database objectcreated in theinit method described inInitializing a Servlet:

public void destroy() {    bookDB = null;}

All of a servlet’s service methods should be complete when a servlet isremoved. The server tries to ensure this by calling thedestroy method onlyafter all service requests have returned or after a server-specific grace period, whichevercomes first. If your servlet has operations that take a long time torun (that is, operations that may run longer than the server’s grace period),the operations could still be running whendestroy is called. You must makesure that any threads still handling client requests complete; the remainder of thissection describes how to do the following:

  • Keep track of how many threads are currently running theservice method.

  • Provide a clean shutdown by having thedestroy method notify long-running threads of the shutdown and wait for them to complete.

  • Have the long-running methods poll periodically to check for shutdown and, if necessary, stop working, clean up, and return.

Tracking Service Requests

To track service requests, include in your servlet class a field that countsthe number of service methods that are running. The field should have synchronizedaccess methods to increment, decrement, and return its value.

public class ShutdownExample extends HttpServlet {    private int serviceCounter = 0;    ...    // Access methods for serviceCounter    protected synchronized void enteringServiceMethod() {        serviceCounter++;    }    protected synchronized void leavingServiceMethod() {        serviceCounter--;    }    protected synchronized int numServices() {        return serviceCounter;    }}

Theservice method should increment the service counter each time the method isentered and should decrement the counter each time the method returns. This isone of the few times that yourHttpServlet subclass should override theservicemethod. The new method should callsuper.service to preserve the functionality of the originalservice method:

protected void service(HttpServletRequest req,                    HttpServletResponse resp)                    throws ServletException,IOException {    enteringServiceMethod();    try {        super.service(req, resp);    } finally {        leavingServiceMethod();    }}

Notifying Methods to Shut Down

To ensure a clean shutdown, yourdestroy method should not release anyshared resources until all the service requests have completed. One part of doingthis is to check the service counter. Another part is to notify thelong-running methods that it is time to shut down. For this notification, anotherfield is required. The field should have the usual access methods:

public class ShutdownExample extends HttpServlet {    private boolean shuttingDown;    ...    //Access methods for shuttingDown    protected synchronized void setShuttingDown(boolean flag) {        shuttingDown = flag;    }    protected synchronized boolean isShuttingDown() {        return shuttingDown;    }}

Here is an example of thedestroy method using these fields to providea clean shutdown:

public void destroy() {    /* Check to see whether there are still service methods /*    /* running, and if there are, tell them to stop. */    if (numServices() > 0) {        setShuttingDown(true);    }    /* Wait for the service methods to stop. */    while(numServices() > 0) {        try {            Thread.sleep(interval);        } catch (InterruptedException e) {        }    }}

Creating Polite Long-Running Methods

The final step in providing a clean shutdown is to make any long-runningmethods behave politely. Methods that might run for a long time should checkthe value of the field that notifies them of shutdowns and should interrupttheir work, if necessary.

public void doPost(...) {    ...    for(i = 0; ((i < lotsOfStuffToDo) &&         !isShuttingDown()); i++) {        try {            partOfLongRunningOperation(i);        } catch (InterruptedException e) {            ...        }    }}
PreviousContentsNext

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


[8]ページ先頭

©2009-2025 Movatter.jp