[Top] [Prev] [Next] [Bottom]

About Java Servlets

JavaTM servlets are small, platform-independent Java programs that can be used to extend the functionality of a Web server in a variety of ways. Servlets are to the server what applets are to the client-small Java programs compiled to bytecode that can be loaded dynamically and that extend the capabilities of the host.

Servlets differ from applets in that servlets do not run in a Web browser or with a graphical user interface. Instead, servlets interact with the servlet engine running on the Web server through requests and responses. The request-response paradigm is modeled on the behavior of the HyperText Transfer Protocol (HTTP).

A client program, which could be a Web browser or some other program that can make connections across the Internet, accesses a Web server and makes a request. This request is processed by the servlet engine that runs with the Web server, which returns a response to a servlet. The servlet in turn sends a response in HTTP form to the client.

In functionality, servlets lie somewhere between Common Gateway Interface (CGI) programs and proprietary server extensions such as the Netscape Server API (NSAPI). Unlike CGI programs and NSAPI modules, you do not need to modify servlets to be platform or server specific.

Overview of Java Servlets

Servlets have the following advantages over other common server extension mechanisms:

The methods described in this specification are methods in the classes and interfaces of the Java Servlet API. For more information, refer to the API reference in Chapter 2.

Servlet Lifecycle

A Java servlet has a lifecycle that defines how the servlet is loaded and initialized, how it receives and responds to requests, and how it is taken out of service. In code, the servlet lifecycle is defined by the javax.servlet.Servlet interface.

All Java servlets must, either directly or indirectly, implement the javax.servlet.Servlet interface so that they can run in a servlet engine. The servlet engine is a customized extension to a Web server for processing servlets, built in conformance with the Java Servlet API by the Web server vendor. The servlet engine provides network services, understands MIME requests, and runs servlet containers.

The javax.servlet.Servlet interface defines methods that are called at specific times and in a specific order during the servlet lifecycle. The entire servlet lifecycle is shown in FIGURE 1-1.

The Servlet Lifecycle

How a Servlet is Loaded and Instantiated

The servlet engine instantiates and loads a servlet. The instantiation and loading can occur when the engine starts, when it needs the servlet in order to respond to a request, or any time in between.

The servlet engine loads a servlet using the Java class loading facility. The servlet engine can load the servlet from the local file system, a remote file system, or a network source.

How a Servlet is Initialized

After the servlet engine loads the servlet, the engine must initialize the servlet. Initialization is a good time for a servlet to read any persistent data it may have stored, initialize JDBC database connections, and establish references to other costly resources.

During initialization, the init method of the javax.servlet.Servlet interface gives the servlet initialization information, so that the servlet has an opportunity to configure itself.

The init method takes a servlet configuration object (of type ServletConfig) as a parameter. The servlet configuration object is implemented in the servlet engine and allows the servlet to access name-value parameters from the engine's configuration information. The servlet configuration object also gives the servlet access to a servlet context object, of type ServletContext.

How a Servlet Handles Requests

After the servlet is initialized, it is ready to handle requests from the client. Each client request that is made of a servlet is represented by a servlet request object (of type ServletRequest). The response the servlet sends to the client is represented by a servlet response object (of type ServletResponse).

When the client makes a request, the servlet engine passes both the servlet request object and the servlet response object to the servlet. The objects are passed as parameters to the service method, defined in the Service interface and which the servlet implements.

The servlet can also implement the ServletRequest or ServletResponse interfaces, or both. The ServletRequest interface gives the servlet access to the request parameters the client sends, such as form data, request information, and protocol methods. The servlet can read the request data from an input stream object (of type ServletInputStream).

The ServletResponse interface allows the servlet to set response headers and status codes. By implementing ServletResponse, the servlet has access to an output stream object (of type ServletOutputStream) that it can use to return data to the client.

Multithreading and Mapping

In a multithreaded environment, most servlets must be written to handle multiple concurrent requests. The exception is a servlet that implements the SingleThreadModel interface. Such a servlet will execute only one request thread at a time.

A servlet responds to a client request according to the servlet engine's mapping. A mapping pairs a servlet instance with an URL to which the servlet returns data, for example, HelloServlet with /hello/index.html.

However, a mapping might pair an URL with more than one servlet instance. For example, a distributed servlet engine running on more than one server might have a servlet instance running on each server, to balance the processing load. As a servlet developer, you cannot assume that a servlet has only one instance.

How a Servlet is Destroyed

The servlet engine is not required to keep a servlet loaded for any period of time or for the life of the server. Servlet engines are free to use servlets or retire them at any time. Therefore, you should not rely on class or instance members to store state information.

When the servlet engine determines that a servlet should be destroyed (for example, if the engine is shut down or needs to conserve resources), the engine must allow the servlet to release any resources it is using and save persistent state. To do this, the engine calls the servlet's destroy method.

The servlet engine must allow any calls to the service method either to complete or to end with a time out (as the engine defines a time out) before the engine can destroy the servlet. Once the engine destroys a servlet, the engine cannot route any more requests to the servlet. The engine must release the servlet and make it eligible for garbage collection.

Servlet Mapping Techniques

As a servlet engine developer, you have a great deal of flexibility in how you map client requests to servlets. This specification does not mandate how the mapping should take place. However, you should feel free to use any of the following techniques:

n You can map a servlet to just one URL.

For example, you can specify that a particular servlet is only called by requests from the file URL /feedback/index.html.

n You can map a servlet to any URL that begins with a certain directory name.

For example, if you map a servlet to the URL /catalog, requests from /catalog/, /catalog/garden, and /catalog/housewares/index.html would also map to the servlet. However, requests from /catalogtwo or /catalog.html would not.

n You can map a servlet to any URL that ends with a certain file name extension.

For example, you can map a request for any file whose name ends in .thtml to a particular servlet. If you use both file name extension mapping and directory mapping in your servlet engine, design the engine so that the file name resolution takes place after the directory name resolution fails.

n You can map a servlet by using the special URL /servlet/servlet_name.

For example, if you create a servlet with the name listattributes, you can access the servlet by using the URL /servlet/listattributes.

n You can invoke a servlet by its class name.

For example, if a servlet engine receives a request from the URL /servlet/com.foo.servlet.MailServlet, the servlet engine can load the class com.foo.servlet.MailServlet, instantiate it, cast the instance to a servlet, and then let the servlet handle the request.

The Servlet Context

The ServletContext interface defines a servlet context object, that is, an object that defines the servlet's view of the servlet engine. By using a servlet context, servlets can log events and obtain resources and objects (such as RequestDispatcher objects) from the servlet engine. A servlet can run in only one servlet context, but different servlets can have different views of the servlet engine.

If a servlet engine supports virtual hosts, each virtual host has a servlet context. A servlet context cannot be shared across virtual hosts.

Servlet engines can allow a servlet context to have as its scope part of a server's URL path.

For example, a servlet context belonging to a bank application can be mapped to the path /bank. In this case, a call to the getContext method (/bank/foo) would return the servlet context for /bank. Such a mapping will become part of the upcoming Deployment Descriptor specification.

HTTP Sessions

The HyperText Transfer Protocol (HTTP) is a stateless protocol. To build effective Web server applications, you must be able to identify a series of unique requests from a remote client as being from the same client. Many strategies for session tracking have evolved over time, but all are difficult or troublesome to use.

The Java Servlet API provides a simple interface that allows a servlet engine to use any number of approaches to track a user session.

Creating a Session

Because HTTP is a request-response protocol, a session is considered new until the client joins it. Join means that the client returns session tracking information to the server, indicating that a session has been established. Until the client joins a session, you cannot assume that the next client response is part of the current session.

The session is considered to be new if either of the following is true:

n The client does not yet know about the session.

n The client chooses not to join a session, for example, if the client declines to accept cookies sent by the server.

As a servlet developer, you must design your Web application to handle situations in which a client has not, or can not, join a session. The server will maintain the session object for a period of time specified by the Web server or a servlet. When a session expires, the server will release the session object and all other objects bound during the session.

Binding Objects into a Session

You might want to bind objects into a session, if it helps you handle your application's data requirements. You can bind any object into a session by a unique name, using the HttpSession object. Any object bound into a session is available to any other servlet that handles a request from the same session.

Some objects may require that you know when they are placed into, or removed from, a session. You can obtain this information by using the HttpSessionBindingListener interface. When your application stores data in or removes data from the session, the servlet engine checks whether the object being bound or unbound implements HttpSessionBindingListener. If it does, methods in the interface notify the object that it has been bound or unbound.



[Top] [Prev] [Next] [Bottom]

servletapi-feedback@eng.sun.com
Copyright © 1998, Sun Microsystems, Inc. All rights reserved.