Oracle JavaServer Pages Developer's Guide and Reference Release 8.1.7 Part Number A83726-01 |
Library | Service | Contents | Index

## Background on Servlets

Because JSP pages are translated into Java servlets, a brief review of servlet technology may be helpful. Refer to the Sun Microsystems Java Servlet Specification, Version 2.2 for more information about the concepts discussed here.

For more information about the methods this section discusses, refer to Sun Microsystems Javadoc at the following location:

    http://java.sun.com/products/servlet/2.2/javadoc/index.html

### Review of Servlet Technology

In recent years, servlet technology has emerged as a powerful way to extend Web server functionality through dynamic HTML pages. A servlet is a Java program that runs in a Web server (as opposed to an applet, which is a Java program that runs in a client browser). The servlet takes an HTTP request from a browser, generates dynamic content (such as by querying a database), and provides an HTTP response back to the browser.

Prior to servlets, CGI (Common Gateway Interface) technology was used for dynamic content, with CGI programs being written in languages such as Perl and being called by a Web application through the Web server. CGI ultimately proved less than ideal, however, due to its architecture and scalability limitations.

Servlet technology, in addition to improved scalability, offers the well-known Java advantages of object orientation, platform independence, security, and robustness. Servlets can use all standard Java APIs, including the JDBC API (for Java database connectivity, of particular interest to database programmers).

In the Java realm, servlet technology offers advantages over applet technology for server-intensive applications such as those accessing a database. One advantage is that a servlet runs in the server, which is usually a robust machine with many resources, minimizing use of client resources. An applet, by contrast, is downloaded into the client browser and runs there. Another advantage is more direct access to the data. The Web server or data server in which a servlet is running is on the same side of the network firewall as the data being accessed. An applet running on a client machine, outside the firewall, requires special measures (such as signed applets) to allow the applet to access any server other than the one from which it was downloaded.

### The Servlet Interface

A Java servlet, by definition, implements the standard `javax.servlet.Servlet` interface. This interface specifies methods to initialize a servlet, process requests, get the configuration and other basic information of a servlet, and terminate a servlet instance.

For Web applications, the `Servlet` interface is implemented indirectly by subclassing the standard `javax.servlet.http.HttpServlet` abstract class. The `HttpServlet` class includes the following methods:

- `init(...)` and `destroy(...)`, to initialize and terminate the servlet, respectively

- `doGet(...)`, for HTTP `GET` requests

- `doPost(...)`, for HTTP `POST` requests

- `doPut(...)`, for HTTP `PUT` requests

- `doDelete(...)`, for HTTP `DELETE` requests

- `service(...)`, to receive HTTP requests and, by default, dispatch them to the appropriate `doXXX()` methods

- `getServletInfo(...)`, which the servlet uses to provide information about itself

A servlet class that subclasses `HttpServlet` must implement some of these methods, as appropriate. Each method takes as input a standard `javax.servlet.http.HttpServletRequest` instance and a standard `javax.servlet.http.HttpServletResponse` instance.

The `HttpServletRequest` instance provides information to the servlet regarding the HTTP request, such as request parameter names and values, the name of the remote host that made the request, and the name of the server that received the request. The `HttpServletResponse` instance provides HTTP-specific functionality in sending the response, such as specifying the content length and MIME type and providing the output stream.

### Servlet Containers

Servlet containers, sometimes referred to as servlet engines, execute and manage servlets. A servlet container is usually written in Java and is either part of a Web server (if the Web server is also written in Java) or otherwise associated with and used by a Web server.

When a servlet is called (such as when a servlet is specified by URL), the Web server passes the HTTP request to the servlet container. The container, in turn, passes the request to the servlet. In the course of managing a servlet, a simple container performs the following:

- creates an instance of the servlet and calls its `init()` method to initialize it

- calls the `service()` method of the servlet

- calls the `destroy()` method of the servlet to discard it when appropriate, so that it can be garbage collected

  For performance reasons, it is typical for a servlet container to keep a servlet instance in memory for reuse, rather than destroying it each time it has finished its task. It would be destroyed only for infrequent events, such as Web server shutdown.

If there is an additional servlet request while a servlet is already running, servlet container behavior depends on whether the servlet uses a single-thread model or a multiple-thread model. In a single-thread case, the servlet container prevents multiple simultaneous `service()` calls from being dispatched to a single servlet instance--it may spawn multiple separate servlet instances instead. In a multiple-thread model, the container can make multiple simultaneous `service()` calls to a single servlet instance, using a separate thread for each call, but the servlet developer is responsible for managing synchronization.

### Servlet Sessions

Servlets use HTTP sessions to keep track of which user each HTTP request comes from, so that a group of requests from a single user can be managed in a stateful way. Servlet session-tracking is similar in nature to HTTP session-tracking in previous technologies, such as CGI.

#### HttpSession Interface

In the standard servlet API, each user is represented by an object that implements the standard `javax.servlet.http.HttpSession` interface. Servlets can set and get information about the session in this `HttpSession` object, which must be of application-level scope.

A servlet uses the `getSession()` method of an `HttpServletRequest` object (which represents an HTTP request) to retrieve or create an `HttpSession` object for the user. This method takes a boolean argument to specify whether a new session object should be created for the user if one does not already exist.

The `HttpSession` interface specifies the following methods to get and set session information:

- `public void setAttribute(String name, Object value)`

  This binds the specified object to the session, under the specified name.

- `public Object getAttribute(String name)`

  This retrieves the object that is bound to the session under the specified name (or `null` if there is no match).

  Note: Older servlet implementations use `putValue()` and `getValue()` instead of `setAttribute()` and `getAttribute()`, with the same signatures.

Depending on the implementation of the servlet container and the servlet itself, sessions may expire automatically after a set amount of time or may be invalidated explicitly by the servlet. Servlets can manage session lifecycle with the following methods, specified by the `HttpSession` interface:

- `public boolean invalidate()`

  This method immediately invalidates the session and unbinds any objects from it.

- `public boolean setMaxInactiveInterval(int interval)`

  This method sets a timeout interval, in seconds, as an integer.

- `public boolean isNew()`

  This method returns `true` within the request that created the session; it returns `false` otherwise.

- `public boolean getCreationTime()`

  This method returns the time when the session object was created, measured in milliseconds since midnight January 1, 1970.

- `public boolean getLastAccessedTime()`

  This method returns the time of the last request associated with the client, measured in milliseconds since midnight January 1, 1970.

#### Session Tracking

The `HttpSession` interface supports alternative mechanisms for tracking sessions. Each involves some way to assign a session ID. A session ID is an intermediate handle that is assigned and used by the servlet container. Multiple sessions by the same user can share the same session ID, if appropriate.

The following session-tracking mechanisms are supported:

- cookies

  The servlet container sends a cookie to the client, which returns the cookie to the server upon each HTTP request. This associates the request with the session ID indicated by the cookie. `JSESSIONID` must be the name of the cookie.

  This is the most frequently used mechanism and is supported by any servlet container that adheres to the servlet 2.2 specification.

- URL rewriting

  The servlet container appends a session ID to the URL path. The name of the path parameter must be `jsessionid`, as in the following example:

      http://host[:port]/myapp/index.html;jsessionid=6789

  This is the most frequently used mechanism where clients do not accept cookies.

- SSL Sessions

  SSL (Secure Sockets Layer, used in the HTTPS protocol) includes a mechanism to take multiple requests from a client and define them as belonging to a single session. Some servlet containers use the SSL mechanism for their own session tracking as well.

### Servlet Contexts

A servlet context is used to maintain state information for all instances of a Web application within any single Java virtual machine (that is, for all servlet and JSP page instances that are part of the Web application). This is similar to the way a session maintains state information for a single client on the server; however, a servlet context is not specific to any single user and can handle multiple clients. There is usually one servlet context for each Web application running within a given Java virtual machine. You can think of a servlet context as an "application container".

Any servlet context is an instance of a class that implements the standard `javax.servlet.ServletContext` interface, with such a class being provided with any Web server that supports servlets.

A `ServletContext` object provides information about the servlet environment (such as name of the server) and allows sharing of resources between servlets in the group, within any single JVM. (For servlet containers supporting multiple simultaneous JVMs, implementation of resource-sharing varies.)

A servlet context maintains the session objects of the users who are running the application and provides a scope for the running instances of the application. Through this mechanism, each application is loaded from a distinct class loader and its runtime objects are distinct from those of any other application. In particular, the `ServletContext` object is distinct for an application, as is the `HttpSession` object for each user of the application.

As of the Sun Microsystems Java Servlet Specification, Version 2.2, most implementations can provide multiple servlet contexts within a single host, which is what allows each Web application to have its own servlet context. (Previous implementations usually provided only a single servlet context with any given host.)

The `ServletContext` interface specifies methods that allow a servlet to communicate with the servlet container that runs it, which is one of the ways that the servlet can retrieve application-level environment and state information.

Note: In earlier versions of the servlet specification, the concept of servlet contexts was not sufficiently defined. Beginning with version 2.1(b), however, the concept was further clarified and it was specified that an HTTP session object could not exist across multiple servlet context objects.

### Application Lifecycle Management Through Event Listeners

The Java Servlet Specification, Version 2.1 (and higher) provides limited application lifecycle management through the standard Java event-listener mechanism. HTTP session objects can use event listeners to make objects stored in the session object aware of when they are added or removed. Because the typical reason for removing objects within a session object is that the session has become invalid, this mechanism allows the developer to manage session-based resources. Similarly, the event-listener mechanism also allows the managing of page-based and request-based resources.

Unfortunately, servlet context objects do not support this sort of notification. Standard servlet application support does not provide a way to manage application-based resources.

### Servlet Invocation

A servlet, like an HTML page, is invoked through a URL. The servlet is launched according to how servlets are mapped to URLs in the Web server implementation. Following are the possibilities:

- A specific URL can be mapped to a specific servlet class.

- An entire directory can be mapped so that any class in the directory is executed as a servlet. For example, the special `/servlet` directory can be mapped so that any URL of the form `/servlet/<``servlet_name``>` executes a servlet.

- A file name extension can be mapped, so that any URL specifying a file whose name includes that extension executes a servlet.

This mapping would be specified as part of the Web server configuration.

| Copyright © 1996-2000, Oracle Corporation. All Rights Reserved. |
Library | Service | Contents | Index