Skip Headers
Oracle® Application Server Containers for J2EE Support for JavaServer Pages Developer's Guide
10g Release 2 (10.1.2)
B14014-02
  Go To Documentation Library
Home
Go To Product List
Solution Area
Go To Table Of Contents
Contents
Go To Index
Index

Previous
Previous
Next
Next
 

A Servlet and JSP Technical Background

This appendix provides technical background on servlets and JavaServer Pages. Although this document is written for users who are well grounded in servlet technology, the servlet information here might be a useful refresher for some.

Standard JavaServer Pages interfaces, implemented automatically by generated JSP page implementation classes, are briefly discussed as well. Most readers, however, will not require this information.

The following sections are included:


Note:

For more information about servlets and the OC4J servlet container, refer to the Oracle Application Server Containers for J2EE Servlet Developer's Guide.

Background on Servlets

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

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

http://java.sun.com/products/servlet/2.3/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 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, you can implement the Servlet interface by extending 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(...): for use by the servlet to provide information about itself

A servlet class that extends 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:

  • It creates an instance of the servlet and calls its init() method to initialize it.

  • It calls the service() method of the servlet.

  • It 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. Multiple separate servlet instances are spawned 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 instance of a class 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 method binds the specified object to the session, under the specified name.

  • public Object getAttribute(String name)

    This method 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 can expire automatically after a set amount of time or can 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. This is the most frequently used mechanism and is supported by any servlet container that adheres to the servlet 2.2 or higher specification.

  • URL rewriting

    The servlet container appends a session ID to the URL path, 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.

Servlet Contexts

A servlet context is used to maintain state information for all instances of a Web application within any single JVM (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 JVM. 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 classloader 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.

Beginning with the servlet 2.2 specification, 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 early 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 servlet 2.2 specification first provided 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.

The servlet 2.3 specification introduced additional support for event listeners, defining interfaces you can implement for event listeners that can be informed of changes in the servlet context lifecycle, servlet context attributes, the HTTP session lifecycle, and HTTP session attributes. See the Oracle Application Server Containers for J2EE Servlet Developer's Guide for more information.

Servlet Invocation

A servlet, like an HTML page, can be directly 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 /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. In OC4J, this is according to settings in the global-web-application.xml file.

A servlet can also be invoked indirectly, like a JSP page, such as through a jsp:include or jsp:forward tag. See "Invoking a Servlet from a JSP Page".

Web Application Hierarchy

The entities relating to a Web application (which consists of some combination of servlets and JSP pages) do not follow a simple hierarchy but can be considered in the following order:

  1. Servlet objects (including page implementation objects)

    There is a servlet object for each servlet and for each JSP page implementation in a running application (and possibly more than one object, depending on whether a single-thread or multiple-thread execution model is used). A servlet object processes request objects from a client and sends response objects back to the client. A JSP page, as with servlet code, specifies how to create the response objects.

    You can think of multiple servlet objects as being within a single request object in some circumstances, such as when one page or servlet includes or forwards to another.

    A user will typically access multiple servlet objects in the course of a session, with the servlet objects being associated with the session object.

    Servlet objects, as well as page implementation objects, indirectly implement the standard javax.servlet.Servlet interface. For servlets in a Web application, this is accomplished by subclassing the standard javax.servlet.http.HttpServlet abstract class. For JSP page implementation classes, this is accomplished by implementing the standard javax.servlet.jsp.HttpJspPage interface.

  2. Request and response objects

    These objects represent the individual HTTP requests and responses that are generated as a user runs an application.

    A user will typically generate multiple requests and receive multiple responses in the course of a session. The request and response objects are not contained in the session, but are associated with the session.

    As a request comes in from a client, it is mapped to the appropriate servlet context object (the one associated with the application the client is using) according to the virtual path of the URL. The virtual path will include the root path of the application.

    A request object implements the standard javax.servlet.http.HttpServletRequest interface.

    A response object implements the standard javax.servlet.http.HttpServletResponse interface.

  3. Session objects

    Session objects store information about the user for a given session and provide a way to identify a single user across multiple page requests. There is one session object for each user.

    There can be multiple users of a servlet or JSP page at any given time, each represented by their own session object. All these session objects, however, are maintained by the servlet context that corresponds to the overall application. In fact, you can think of each session object as representing an instance of the Web application associated with a common servlet context.

    Typically, a session object will sequentially make use of multiple request objects, response objects, and page or servlet objects, and no other session will use the same objects; however, the session object does not actually contain those objects.

    A session lifecycle for a given user starts with the first request from that user. It ends when the user session terminates (such as when the user quits the application or there is a timeout).

    HTTP session objects implement the javax.servlet.http.HttpSession interface.


    Note:

    Prior to the 2.1(b) version of the servlet specification, a session object could span multiple servlet context objects.

  4. Servlet context object

    A servlet context object is associated with a particular path in the server. This is the base path for modules of the application associated with the servlet context, and is referred to as the application root.

    There is a single servlet context object for all sessions of an application in any given JVM, providing information from the server to the servlets and JSP pages that form the application. The servlet context object also allows application sessions to share data within a secure environment isolated from other applications.

    The servlet container provides a class that implements the standard javax.servlet.ServletContext interface, instantiates this class the first time a user requests an application, and provides this ServletContext object with the path information for the location of the application.

    The servlet context object typically has a pool of session objects to represent the multiple simultaneous users of the application.

    A servlet context lifecycle starts with the first request (from any user) for the corresponding application. The lifecycle ends only when the server is shut down or otherwise terminated.

    For additional introductory information about servlet contexts, see "Servlet Contexts".

  5. Servlet configuration object

    The servlet container uses a servlet configuration object to pass information to a servlet when it is initialized. The init() method of the Servlet interface takes a servlet configuration object as input.

    The servlet container provides a class that implements the standard javax.servlet.ServletConfig interface and instantiates it as necessary. Included within the servlet configuration object is a servlet context object (also instantiated by the servlet container).

Standard JSP Interfaces and Methods

Two standard interfaces, both in the javax.servlet.jsp package, are available to be implemented in code that is generated by a JSP translator:

JspPage is a generic interface that is not intended for use with any particular protocol. It extends the javax.servlet.Servlet interface.

HttpJspPage is an interface for JSP pages using the HTTP protocol. It extends JspPage and is typically implemented directly and automatically by any servlet class generated by a JSP translator.

JspPage specifies the following methods for use in initializing and terminating instances of the generated class:

If you want any special initialization or termination functionality, you must provide a JSP declaration to override the relevant method, as in the following example:

<%! void jspInit()
    {
        ...your implementation code...
    }
%>

HttpJspPage adds specification of the following method:

Code for this method is typically generated automatically by the translator and includes the following:

(JSP directives provide information for the page, such as specifying the Java language for scriptlets and providing package imports. See "Directives".)

As with the Servlet methods, the _jspService() method takes an HttpServletRequest instance and an HttpServletResponse instance as input.

The JspPage and HttpJspPage interfaces inherit the following methods from the Servlet interface:

Refer back to "The Servlet Interface" for a discussion of the Servlet interface and its key methods.