Skip Headers
Oracle® Containers for J2EE Servlet Developer's Guide
10g Release 3 (10.1.3)
B14426-01
  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
 

1 Summary of What to Know About Servlets

Oracle Containers for J2EE (OC4J) enables you to develop and deploy standard J2EE-compliant applications. Applications are packaged in standard Enterprise archive (EAR) deployment files, which include standard Web archive (WAR) files to deploy the Web modules, resource adapter archive (RAR) files for resource adapters, and Java archive (JAR) files for any Enterprise JavaBeans (EJB) and application client modules in the application.

With Oracle Application Server 10g Release 3 (10.1.3), OC4J complies with Java 2 Platform Enterprise Edition Specification, v1.4, including full compliance with the Sun Microsystems Java Servlet Specification, Version 2.4 in the OC4J servlet container. (Any mention of the servlet specification in this manual refers to this version unless otherwise noted.)


Note:

Servlets in this release require HTTP/1.1 and Java 2 Standard Edition (J2SE) 1.3 or higher.

This chapter, containing the following sections, provides an overview of servlet technology and concludes with a summary of servlet features:

You can find the servlet specification at the following location:

http://java.sun.com/products/servlet/reference/api/index.html

Note:

Sample servlet applications are included in the OC4J demos, available from the following location on the Oracle Technology Network (requiring an OTN membership, which is free of charge):
http://www.oracle.com/technology/tech/java/oc4j/demos/index.html

Summary of Servlet and J2EE Technology

The following sections offer a brief introduction to servlet and other J2EE technology:


Note:

The terms Web module and Web application are interchangeable in most uses and are both used throughout this document. If there is a distinction, it is that "Web module" typically indicates a single component, whether or not it composes an independent application, while "Web application" typically indicates a working application that may consist of multiple modules or components.

The Essence of Servlets

In recent years, servlet technology has emerged as a powerful way to extend Web server functionality through dynamic Web pages. A servlet is a Java program that runs in a Web server, as opposed to an applet that runs in a client browser. Typically, 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. Alternatively, the servlet can be accessed directly from another application component or send its output to another component. Most servlets generate HTML text, but a servlet may instead generate XML to encapsulate data.

More specifically, a servlet runs in a J2EE application server, such as OC4J. Servlets are one of the main application component types of a J2EE application, along with JavaServer Pages (JSP) and Enterprise JavaBeans (EJB) modules, which are also server-side J2EE component types. These are used in conjunction with client-side components such as applets (part of the Java 2 Platform, Standard Edition specification) and application client programs. An application may consist of any number of any of these components.

Prior to servlets, Common Gateway Interface (CGI) 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.

Why Use Servlets?

In the Java realm, servlet technology offers advantages over applet technology for server-intensive applications, such as those accessing a database. One advantage of running in the server is that the server is usually a robust machine with many resources, making the program more scalable. Running in the server also results in 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.

Servlet programming also offers advantages over earlier models of server-side Web application development, including the following:

  • Servlets outperform earlier technologies for generating dynamic HTML, such as server-side "includes" or CGI scripts. After a servlet is loaded into memory, it can run on a single lightweight thread; CGI scripts must be loaded in a different process for each request.

  • Servlet technology, in addition to improved scalability, offers the well-known Java advantages of security, robustness, object orientation, and platform independence.

  • Servlets are fully integrated with the Java language and its standard APIs, such as JDBC for Java database connectivity.

  • Servlets are fully integrated into the J2EE framework, which provides an extensive set of services that your Web application can use, such as Java Naming and Directory Interface (JNDI) for component naming and lookup, Java Transaction API (JTA) for managing transactions, Java Authentication and Authorization Service (JAAS) for security, Remote Method Invocation (RMI) for distributed applications, and Java Message Service (JMS). The following Web site contains information about the J2EE framework and services:

    http://java.sun.com/j2ee/docs.html
    
    
  • A servlet handles concurrent requests (through either a single servlet instance or multiple servlet instances, depending on the thread model), and servlets have a well-defined lifecycle. In addition, servlets can optionally be loaded when OC4J starts, so that any initialization is handled in advance instead of at the first user request. See "Preloading Servlets".

  • The servlet request and response objects offer a convenient way to handle HTTP requests and send text and data back to the client.

Because servlets are written in the Java programming language, they are supported on any platform that has a Java virtual machine (JVM) and a Web server that supports servlets. Servlets can be used on different platforms without recompiling. You can package servlets together with associated files such as graphics, sounds, and other data to make a complete Web application. This simplifies application development and deployment.

In addition, you can port a servlet-based application from another Web server to OC4J with little effort. If your application was developed for a J2EE-compliant Web server, then the porting effort is minimal.

Servlet Lifecycle

Servlets have a predictable and manageable lifecycle:

  • When the servlet is loaded, its configuration details are read from the standard web.xml Web module configuration file. These details can include initialization parameters.

  • There is only one instance of a servlet, unless the single-threaded model is used. See "Servlet Thread Models".

  • Client requests invoke the central service() method of the servlet, which then delegates the request to doGet() (for HTTP GET requests), doPost() (for HTTP POST requests), or some other overridden request-handling method, depending on the information in the request headers.

  • Filters can be interposed between the container and the servlet to modify the servlet behavior, either during request or response. See Chapter 5, "Understanding and Using Servlet Filters" for more information.

  • A servlet can forward requests to other servlets or include output from other servlets. See "Dispatching to Other Servlets Through Includes and Forwards".

  • Responses come back to the client through response objects, which the container passes back to the client in HTTP response headers. Servlets can write to a response object by using a java.io.PrintWriter or javax.servlet.ServletOutputStream object.

  • The container calls the destroy() method before the servlet is unloaded.

JSP Pages and Other J2EE Component Types

In addition to servlets, an application may include other server-side components, such as JSP pages and EJBs. Servlets are managed by the OC4J servlet container; EJBs are managed by the OC4J EJB container; and JSP pages are managed by the OC4J JSP container. These containers form the core of OC4J.

Servlets and JSP pages have a particularly close correspondence. Both servlets and JSP pages are referred to as "Web components", and both are configured through the standard web.xml file. A JSP page implementation class, created by the JSP container during translation of a JSP page, is actually a servlet and implements the javax.servlet.Servlet interface, as does any servlet. JSP pages and servlets can be used seamlessly together in creating Web applications.

Servlets or JSP pages often call EJBs to perform further processing. A typical J2EE application uses servlets or JSP pages for the user interface and for initial processing of user requests, then calls EJBs to perform business logic and database access.


Note:

Wherever this manual mentions functionality that applies to servlets, you can assume it applies to JSP pages as well unless stated otherwise.

For more information about JSP pages and EJBs, see the following:

Key Components and APIs of the Servlet Model

This section summarizes important components and programming interfaces of the servlet model, covering the following:

For complete information about APIs mentioned here, see the Sun Microsystems Javadoc for the javax.servlet and javax.servlet.http packages at the following location:

http://java.sun.com/j2ee/1.4/docs/api/index.html

Key Methods of the Servlet Interface

A Java servlet, by definition, implements the 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 remove a servlet instance from service.

For Web applications, you can implement the Servlet interface by extending the javax.servlet.http.HttpServlet abstract class. This class, intended for HTTP servlets suitable for a Web site, extends the javax.servlet.GenericServlet class, which implements the Servlet interface.

The HttpServlet class includes the following methods, which are called by the OC4J servlet container (discussed later in this chapter) during servlet execution, as appropriate. You can write code to override any of them, as desired, to provide functionality in your servlet. See "When to Implement Methods of the Servlet Interface".

  • void init(ServletConfig config)

    Initializes the servlet, preparing it to serve requests. This takes a servlet configuration object, described in "Servlet Configuration Objects", as input. Implement code here for any special startup requirements of your servlet.

  • void destroy()

    Removes the servlet from service. Implement code here for any special shutdown requirements of your servlet, such as releasing resources.

  • void doGet(HttpServletRequest req, HttpServletResponse resp)

    Implement code here to execute an HTTP GET request. HTTP request and response objects are described in the next section, "Servlet Communication: Request and Response Objects"

  • void doPost(HttpServletRequest req, HttpServletResponse resp)

    Implement code here to execute an HTTP POST request.

  • void doPut(HttpServletRequest req, HttpServletResponse resp)

    Implement code here to execute an HTTP PUT request.

  • void doDelete(HttpServletRequest req, HttpServletResponse resp)

    Executes an HTTP DELETE request.

  • String getServletInfo()

    Retrieves information about the servlet, such as author and release date.

Also be aware of the following methods:

  • void service(HttpServletRequest req, HttpServletResponse resp)

    This is the central method of a servlet. It receives HTTP requests and, by default, dispatches them to the appropriate doXXX() methods that you have defined. There is typically no need to override this method.

  • ServletConfig getServletConfig()

    Retrieves the servlet configuration object, which contains initialization and startup parameters.

Servlet Communication: Request and Response Objects

Servlet methods mentioned in the preceding section that handle HTTP operations—doGet(), doPost(), doPut(), and doDelete()—take as input an HTTP request object (an instance of a class that implements the javax.servlet.http.HttpServletRequest interface, which extends the javax.servlet.ServletRequest interface) and an HTTP response object (an instance of a class that implements the javax.servlet.http.HttpServletResponse interface, which extends the javax.servlet.ServletResponse interface).

The request object 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 response object provides HTTP-specific functionality in sending the response, such as specifying the content length and MIME type and providing the output stream.

Key Methods of the HttpServletRequest Interface

This section summarizes methods of interest for HTTP request objects. See "Using HTML Forms and Request Parameters" for examples of some of their uses.

The following methods are defined in the HttpServletRequest interface:

  • HttpSession getSession()

    Returns (first creating, if necessary) an object representing the client session associated with this request. See "What are Servlet Sessions (User Sessions) Used For?". You can optionally input the boolean true or false to specify whether you want to create a new session if one does not already exist.

  • Cookie[] getCookies()

    Returns an array of cookie objects for the cookies, used for session tracking, that were sent with this request. See "Using Cookies in Your Servlet".

  • java.lang.StringBuffer getRequestURL()

    Recreates the URL that was used for this request.

  • String getContextPath()

    Returns the context path portion of the URL for this request. This corresponds to the root path of the servlet context for the Web application. See "Summary of URL Components".

  • String getServletPath()

    Returns the servlet path portion of the URL for this request. This is the portion that results in the invocation of the particular servlet being requested, according to configuration in the standard web.xml file.

  • String getRequestURI()

    Returns a portion of the URL for this request, after the host and port and up to the query string (if any). This is typically the context path and servlet path.

  • String getQueryString()

    Returns the query string appended to the URL (if applicable), following the "?" delimiter.

  • String getMethod()

    Returns the HTTP method used with this request, such as GET, POST, or PUT.

  • String getProtocol()

    Returns the protocol (typically HTTP) and version being used.

The following methods are inherited from the ServletRequest interface:

  • String getParameter(String name)

    Returns a string indicating the value of the request parameter specified by name (or null if not found).

  • java.util.Enumeration getParameterNames()

    Returns an enumeration object containing strings that indicate the names of all request parameters for this request.

  • javax.servlet.ServletInputStream getInputStream()

    Retrieves the body of the request in binary format.

  • java.io.BufferedReader getReader()

    Retrieves the body of the request in character format.

  • String getContentType()

    Returns a string indicating the MIME type for the body of this request (or null if the MIME type is unknown).

  • void setCharacterEncoding(String charset)

    Overrides the character encoding (MIME character set) that would otherwise be used for interpreting the body and parameters of this request.

  • String getCharacterEncoding()

    Returns a string indicating the character encoding used for interpreting the body and parameters of this request.

  • RequestDispatcher getRequestDispatcher(String path)

    Returns a "request dispatcher", which is used as a wrapper for the resource at the specified path. See "Dispatching to Other Servlets Through Includes and Forwards".

Key Methods of the HttpServletResponse Interface

This section summarizes methods of interest for HTTP response objects. See "Setting Up the Response" for further information.

The following methods are defined in the HttpServletResponse interface:

  • void sendRedirect(String location)

    For redirects, specify the alternative location (URL) to which the client is being redirected. (One reason for redirection might be load balancing, for example. Or perhaps a document has moved from one URL to another.)

  • String encodeURL(String url)

    For session tracking, when cookies are disabled, this is used in URL rewriting to encode the specified URL with an ID for the session. It returns the encoded URL. See "Using URL Rewriting for Session Tracking".

  • String encodeRedirectURL(String url)

    For redirects, this is equivalent to encodeURL().

  • void addCookie(javax.servlet.http.Cookie cookie)

    For session tracking, when cookies are enabled, this adds the specified cookie to the response. See "Using Cookies in Your Servlet".

  • void sendError(int code)void sendError(int code, String msg)

    Send an error response, with a specified integer error code, to the client. You can optionally specify a descriptive message as well.

The following methods are inherited from the ServletResponse interface:

  • javax.servlet.ServletOutputStream getOutputStream()

    Returns a stream object that can be used for writing binary data into the response to the client.

  • java.io.PrintWriter getWriter()

    Returns a print writer object that can be used for writing character data into the response to the client.

  • void setContentType(String type)

    Specify a MIME type for the body of this response. You can optionally also specify a character encoding (MIME character set). For example, "text/html;charset=UTF-8".

  • String getContentType()

    Returns a string indicating the MIME type for the body of this response. This method also returns the character encoding (MIME character set) if one had been specified.

  • void setCharacterEncoding(String charset)

    Specify a character encoding for the body of this response. Alternatively, you can set a character encoding through the setContentType() method. A setting in setCharacterEncoding() overrides any character encoding set through setContentType().

  • String getCharacterEncoding()

    Returns a string indicating the character encoding for the body of this response.

Servlet Execution in the Servlet Container

Unlike a Java client program, a servlet has no static main() method. Therefore, a servlet must execute under the control of an external container.

Servlet containers, sometimes referred to as servlet engines, execute and manage servlets. The servlet container calls servlet methods and provides services that the servlet needs while executing. 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 is otherwise associated with and used by a Web server. OC4J includes a fully standards-compliant servlet container.

The servlet container provides the servlet with easy access to properties of the HTTP request, such as its headers and parameters. When a servlet is called, such as when it 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 servlet container performs the following tasks:

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

  • It constructs a request object to pass to the servlet. The request includes, among other things:

    • Any HTTP headers from the client

    • Parameters and values passed from the client (for example, names and values of query strings in the URL)

    • The complete URI of the servlet request

  • It constructs a response object for the servlet.

  • It invokes the servlet service() method, implemented in the HttpServlet class. The service method dispatches requests to the servlet doGet() or doPost() methods, depending on the HTTP header in the request (GET or POST).

  • 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.)

Figure 1-1 shows how a servlet relates to the servlet container and to a client, such as a Web browser.

Figure 1-1 Servlets and the Servlet Container

Description of fc01.gif follows
Description of the illustration fc01.gif

Servlet Configuration Objects

A servlet configuration object contains initialization and startup parameters for a servlet and is an instance of a class that implements the javax.servlet.ServletConfig interface. Such a class is provided with any J2EE-compliant Web server.

Obtaining a Servlet Configuration Object

A servlet can retrieve a servlet configuration object through the getServletConfig() method of the servlet. This method is specified in the javax.servlet.Servlet interface, with a default implementation in the javax.servlet.http.HttpServlet class.

The servlet init() method takes a ServletConfig object as input, so if you override the init() method, the servlet will have access to a servlet configuration object that the servlet container creates and passes during servlet execution.

Key Servlet Configuration Methods

The ServletConfig interface specifies the following methods:

  • ServletContext getServletContext()

    Retrieves a servlet context for the application. See the following section, "Servlet Contexts: the Application Container".

  • String getServletName()

    Retrieves the name of the servlet.

  • Enumeration getInitParameterNames()

    Retrieves the names of the initialization parameters of the servlet, if any. The names are returned in a java.util.Enumeration instance of String objects. (The Enumeration instance is empty if there are no initialization parameters.)

  • String getInitParameter(String name)

    Returns a String object containing the value of the specified initialization parameter, or null if there is no parameter by that name.

Servlet Contexts: the Application Container

A servlet context is used to maintain 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). There is one servlet context for each Web application running within a given JVM; this is always a one-to-one correspondence. You can think of a servlet context as a container for a specific application.

Servlet Context Basics

Any servlet context is an instance of a class that implements the 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 the 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 provides the 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, much as each HttpSession object is distinct for each user of the application.

Since version 2.2 of the servlet 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.)

Obtaining a Servlet Context

A servlet can retrieve a servlet context through the getServletContext() method of a servlet configuration object. See "Servlet Configuration Objects".

Key Servlet Context Methods

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. Methods specified in ServletContext include the following:

  • void setAttribute(String name, Object value)

    Binds the specified object to the specified attribute name in the servlet context. Using attributes, a servlet container can give information to the servlet that is not otherwise provided through the ServletContext interface.


    Note:

    For a servlet context, setAttribute() is a local operation only. It is not intended to be distributed to other JVMs within a cluster. (This is in accordance with the servlet specification.)

  • Object getAttribute(String name)

    Returns the attribute with the given name, or null if there is no attribute by that name. The attribute is returned as a java.lang.Object instance.

  • java.util.Enumeration getAttributeNames()

    Returns a java.util.Enumeration instance containing the names of all available attributes of the servlet context.

  • void removeAttribute(String attrname)

    Removes the specified attribute from the servlet context.

  • String getInitParameter(String name)

    Returns a string that indicates the value of the specified context-wide initialization parameter, or null if there is no parameter by that name. This allows access to configuration information that is useful to the Web application associated with this servlet context.

  • Enumeration getInitParameterNames()

    Returns a java.util.Enumeration instance containing the names of the initialization parameters of the servlet context.

  • RequestDispatcher getRequestDispatcher(String path)

    Returns a "request dispatcher" that acts as a wrapper for the resource located at the specified path. See "Dispatching to Other Servlets Through Includes and Forwards".

  • RequestDispatcher getNamedDispatcher(String name)

    Returns a request dispatcher that acts as a wrapper for the specified servlet.

  • String getRealPath(String path)

    Returns the real path, as a string, for the specified virtual path.

  • URL getResource(String path)

    Returns a java.net.URL instance with a URL to the resource that is mapped to the specified path.

  • String getServerInfo()

    Returns the name and version of the servlet container.

  • String getServletContextName()

    Returns the name of the Web application with which the servlet context is associated, according to the <display-name> element of the web.xml file.

What are Servlet Sessions (User Sessions) Used For?

The HTTP protocol is stateless by design. This is fine for stateless servlets that simply take a request, perform a few computations, output some results, and then in effect go away. But most server-side applications must keep some state information and maintain a dialogue with the client. The most common example of this is a shopping cart application. A client accesses the server several times from the same browser and visits several Web pages. The client decides to buy some of the items offered for sale at the Web site and clicks the BUY ITEM buttons. If each transaction were being served by a stateless server-side object, and the client provided no identification on each request, it would be impossible to maintain a filled shopping cart over several HTTP requests from the client. In this case, there would be no way to relate a client to a server session, so even writing stateless transaction data to persistent storage would not be a solution.

Session tracking is a mechanism to identify user sessions and appropriately tie all of a user's requests to his or her session. This process is typically performed using cookies or URL rewriting.

In the standard servlet API, each user session is represented by an instance of a class that implements the javax.servlet.http.HttpSession interface.

See Chapter 4, "Understanding and Using Servlet Sessions" for details.

Servlet Thread Models

For a servlet in a nondistributable environment, a servlet container uses only one servlet instance for each servlet declaration. In a distributable environment, a container uses one servlet instance for each servlet declaration in each JVM. Therefore, a servlet container, including the OC4J servlet container, generally processes concurrent requests to a servlet by using multiple threads for multiple concurrent executions of the central service() method of the servlet.

Servlet developers must keep this in mind, making provisions for simultaneous processing through multiple threads and designing their servlets so that access to shared resources is somehow synchronized or coordinated. See "Considerations for Thread Models" for information.

Servlet Feature Table

Table 1-1 summarizes servlet development features described in this document (some of which have already been discussed), with cross-references for information. Features added in the servlet 2.4 specification are noted.

Table 1-1 Servlet Features in the Current Release

Feature Information
Request and response objects "Servlet Communication: Request and Response Objects"
Servlet container "Servlet Execution in the Servlet Container"
Servlet configuration objects "Servlet Configuration Objects"
Servlet contexts "Servlet Contexts: the Application Container"
Sessions Introduction in "What are Servlet Sessions (User Sessions) Used For?"; details in Chapter 4, "Understanding and Using Servlet Sessions"
Includes and forwards "Dispatching to Other Servlets Through Includes and Forwards"
Servlet filters Introduction in "When to Use Filters for Pre-Processing and Post-Processing"; details in Chapter 5, "Understanding and Using Servlet Filters"

Note: The ability to use filters with include or forward targets was added in the servlet 2.4 specification.

Event listeners Introduction in "When to Use Event Listeners for Servlet Notification"; details in Chapter 6, "Understanding and Using Event Listeners"

Note: Support for request listeners (as opposed to servlet context or session listeners) was added in the servlet 2.4 specification.

Use of JDBC and data sources "Using JDBC in Servlets"
Use of EJBs "Overview of Enterprise JavaBeans"