|OracleJSP Support for JavaServer Pages Developer's Guide and Reference
Part Number A90208-01
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 may 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 topics are covered:
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:
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.
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:
destroy(...), to initialize and terminate the servlet, respectively
doGet(...), for HTTP
doPost(...), for HTTP
doPut(...), for HTTP
doDelete(...), for HTTP
service(...), to receive HTTP requests and, by default, dispatch them to the appropriate
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
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, 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:
init()method to initialize it
service()method of the servlet
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.
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.
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.
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).
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
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
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.
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:
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.
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:
This is the most frequently used mechanism where clients do not accept cookies.
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.
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.
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.)
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.
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.
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:
/servletdirectory can be mapped so that any URL of the form
>executes a servlet.
This mapping would be specified as part of the Web server configuration.
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:
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
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
A response object implements the standard
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 per user.
There may 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 "contain" those objects per se.
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
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 the application in any given JVM, providing information from the server to the servlets and JSP pages that comprise 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".)
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).
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
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 used in initializing and terminating instances of the generated class:
Any code for these methods must be included in scriptlets in your JSP page, as in the following example:
(JSP syntax is described later in this chapter. See "Scripting Elements".)
HttpJspPage adds specification for the following method:
Code for this method is typically generated automatically by the translator and includes the following:
(JSP directives are used to provide information for the page, such as specifying the Java language for scriptlets and providing package imports. See "Directives".)
As with the
Servlet methods discussed in "The Servlet Interface", the
_jspService() method takes an
HttpServiceRequest instance and an
HttpServiceResponse instance as input.
HttpJspPage interfaces inherit the following methods from the
Refer back to "The Servlet Interface" for a discussion of the
Servlet interface and its key methods.