Oracle9iAS Containers for J2EE Servlet Developer's Guide Release 2 (9.0.3) Part Number A97680-01 |
|
Oracle9iAS Containers for J2EE (OC4J) enables you to develop and deploy standard J2EE-compliant applications. Applications are packaged in standard EAR (Enterprise ARchive) deployment files, which include standard WAR (Web ARchive) files to deploy the Web modules, and JAR files for any EJB and application client modules in the application.
With Oracle9iAS release 2 (9.0.3), OC4J complies with the J2EE 1.3 specification, including full servlet 2.3 compliance in the OC4J servlet container.
The most important concepts to understand about servlet development under OC4J are how the Web application is built and how it is deployed. If you are new to servlets, see Chapter 2, "Servlet Development". If OC4J is a new development environment for you, see Chapter 3, "Deployment and Configuration", to learn how applications are deployed under OC4J.
This chapter introduces the Java servlet and provides an example of a basic servlet. It also briefly discusses how you can use servlets in a J2EE application to address some server-side programming issues.
This chapter is organized as follows:
This section offers a brief introduction to servlet technology, covering the following topics:
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, 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.
Most servlets generate HTML text, which is then sent back to the client for display by the Web browser, or is sent on to other components in the application. Servlets can also generate XML, to encapsulate data, and send this to the client or to other components.
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 EJBs, another server-side J2EE component type. These are used in conjunction with client-side components such as applets (part of the Java 2 Standard Edition specification) and application client programs. A Web application might consist of any number of any of these components.
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.
Servlet programming also offers advantages over earlier models of server-side Web application development, including the following:
Because servlets are written in the Java programming language, they are supported on any platform that has a Java virtual machine 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.
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 terminate a servlet instance.
For Web applications, you can implement the Servlet
interface by extending the javax.servlet.http.HttpServlet
abstract class. (Alternatively, for protocol-independent servlets, you can extend the javax.servlet.GenericServlet
class.) The HttpServlet
class includes the following methods:
init(...)
--This is to initialize the servlet.
destroy(...)
--This is to terminate the servlet.
doGet(...)
--This is for HTTP GET
requests.
doPost(...)
--This is for HTTP POST
requests.
doPut(...)
--This is for HTTP PUT
requests.
doDelete(...)
--This is for HTTP DELETE
requests.
service(...)
--This is to receive HTTP requests and, by default, dispatch them to the appropriate do
XXX
()
methods.
getServletInfo(...)
--This is for use by the servlet to provide information about itself.
A servlet class that extends HttpServlet
implements some or all of these methods, as appropriate, overriding the original implementations as necessary to process the request and return the response as desired. For example, most servlets override the doGet()
method or doPost()
method or both to process HTTP GET
and POST
requests.
Each method takes as input an HttpServletRequest
instance (an instance of a class that implements the javax.servlet.http.HttpServletRequest
interface) and an HttpServletResponse
instance (an instance of a class that implements the javax.servlet.http.HttpServletResponse
interface).
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.
Unlike a Java client program (but like an applet), 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. It is the servlet container that calls servlet methods and provides services that the servlet needs when 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 otherwise associated with and used by a Web server.
The servlet container provides the servlet easy access to properties of the HTTP request, such as its headers and parameters. 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 servlet container performs the following tasks:
init()
method to initialize it.
service()
method. Note that for HTTP servlets, the generic service method is usually overridden 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
).
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. When the Web listener is the Oracle HTTP Server (powered by Apache), the connection to the OC4J servlet container goes through the mod_oc4j
module. See the Oracle HTTP Server Administration Guide for details.
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 session tracking in previous technologies, such as CGI.
This section provides an introduction to servlet sessions. See "Servlet Sessions" for more information and examples.
In the standard servlet API, each user is represented by an instance of a class that implements the 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 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 public methods to get and set session information:
void setAttribute(String name, Object value)
This method binds the specified object to the session, under the specified name.
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).
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:
void invalidate()
This method immediately invalidates the session, unbinding any objects from it.
void setMaxInactiveInterval(int interval)
This method sets a session timeout interval, in seconds, as an integer.
boolean isNew()
This method returns true
within the request that created the session; it returns false
otherwise.
long getCreationTime()
This method returns the time when the session object was created, measured in milliseconds since midnight, January 1, 1970.
long getLastAccessedTime()
This method returns the time of the last request associated with the client, measured in milliseconds since midnight, January 1, 1970.
For complete information about HttpSession
methods, you can refer to the Sun Microsystems Javadoc at the following location:
http://java.sun.com/products/servlet/2.3/javadoc/index.html
Servlets provide convenient ways to keep the client and a server session in synchronization, enabling stateful servlets to maintain session state on the server over the whole duration of a client browsing session.
The following session-tracking mechanisms are supported. See "Session Tracking" for more information.
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.
In case cookies might be disabled, the servlet can call the encodeURL()
method of the response object, or the encodeRedirectURL()
method for redirects, to append a session ID to the URL path for each request. This allows the request to be associated with the session. This is the most frequently used mechanism where clients do not accept cookies.
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 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, much as each HttpSession
object is distinct for each user of the application.
Beginning with 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. Methods specified in ServletContext
include those listed here. For complete information, you can refer to the Sun Microsystems Javadoc at the following location:
http://java.sun.com/products/servlet/2.3/javadoc/index.html
void setAttribute(String name, Object value)
This method 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.
Object getAttribute(String name)
This method 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()
This method returns a java.util.Enumeration
instance containing the names of all available attributes of the servlet context.
void removeAttribute(String attrname)
This method removes the specified attribute from the servlet context.
String getInitParameter(String name)
This method 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 (the name of a system that has critical information, for example).
Enumeration getInitParameterNames()
This method returns a java.util.Enumeration
instance containing the names of the initialization parameters of the servlet context.
RequestDispatcher getNamedDispatcher(String name)
This returns a javax.servlet.RequestDispatcher
instance that acts as a wrapper for the specified servlet.
RequestDispatcher getRequestDispatcher(String path)
This returns a javax.servlet.RequestDispatcher
instance that acts as a wrapper for the resource located at the specified path.
String getRealPath(String path)
This returns the real path, as a string, for the specified virtual path.
URL getResource(String path)
This returns a java.net.URL
instance with a URL to the resource that is mapped to the specified path.
String getServerInfo()
This method returns the name and version of the servlet container.
String getServletContextName()
This 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.
Request objects (instances of a class that implements HttpServletRequest
) and response objects (instances of a class that implements HttpServletResponse
) are typically passed directly between the servlet container and a servlet.
The servlet 2.3 specification, however, allows servlet filters, which are Java programs that execute on the server and can be interposed between the servlet (or group of servlets) and the servlet container for special request or response processing.
If there is a filter or a chain of filters to be invoked before the servlet, these are called by the container with the request and response objects as parameters. The filters pass these objects, perhaps modified, or alternatively create and pass new objects, to the next object in the chain using the doChain()
method.
See "Servlet Filters" for more information.
The servlet 2.3 specification adds the capability to track key events in your Web applications, through event listeners. This functionality allows more efficient resource management and automated processing based on event status.
When creating listener classes, there are standard interfaces you can implement for servlet context lifecycle events, servlet context attribute changes, HTTP session lifecycle events, and HTTP session attribute changes. A listener class can implement one, some, or all of the interfaces as appropriate.
An event listener class is declared in the web.xml
deployment descriptor and invoked and registered upon application startup. When an event occurs, the servlet container calls the appropriate listener method.
See "Event Listeners" for more information.
In addition to servlets, a Web application might include other server-side components such as JavaServer Pages (JSP) and Enterprise JavaBeans (EJB).
While 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.
JSP pages also involve the servlet container, because the JSP container itself is a servlet and is therefore executed by the servlet container. The JSP container translates JSP pages into page implementation classes, which are executed by the JSP container but function similarly to servlets.
For more information about JSP pages and EJBs, see the following:
Looking at a basic example is the best way to demonstrate the general framework for writing a servlet. This section shows the code for a simple servlet, but with a twist for globalization. The code is commented to explain the basics of servlet development.
This servlet prints the date and a greeting back to the client, but in Swedish.
Here is the code:
import java.io.*; import java.text.*; import java.util.*; // The first three package imports support I/O, and the locale info and date // formatting. The next two imports include the packages that support // servlet development. import javax.servlet.*; import javax.servlet.http.*; // HTTP servlets extend the javax.servlet.http.HttpServlet class. public class HelloWorldServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // doGet() overrides the HttpServlet method. Each method of this class // has request and/or response parameters. // Set the content type of the response. res.setContentType("text/plain"); // Get a print writer stream to write output to the response. You // could also get s ServletOutputStream object to do this. PrintWriter out = res.getWriter(); // This statement tells the client the language of the content--Swedish. // However, many Web browsers will ignore this info. res.setHeader("Content-Language", "sv"); // Set the locale information, so the date will be formatted in a Swedish- // friendly way, and the right words are used for months and so on. Locale locale = new Locale("sv", ""); // Get the date format. DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); // Also set the local time zone. dateFormat.setTimeZone(TimeZone.getDefault()); // Now use the printer object to send some HTML header info to the // output stream. out.println("<HTML><HEAD><TITLE>Hej V\u00e4rlden!</TITLE></HEAD>"); out.println("<BODY>"); // Send the date to the output. out.println(dateFormat.format(new Date())); // And then, greet the client-- out.println("<p>In Swedish (p\u00E5 Svenska):"); out.println("<H2>Hej V\u00E4rlden!</H2>"); // Don't forget to close the HTML tags. out.println("</BODY></HTML>"); } }
To try out this servlet in your OC4J server, enter the code using your favorite text editor, and save it as HelloWorldServlet.java
in the /WEB-INF/classes
directory of the OC4J default Web application. (See "OC4J Default Web Application and Key Directories".) Next, compile the servlet, using a Java 1.3.x-compliant compiler.
For convenience during development and testing, use the OC4J auto-compile feature for servlet code. This is enabled through the setting development="true"
in the <orion-web-app>
element of the global-web-application.xml
file in the OC4J configuration files directory. The source-directory
attribute may also have to be set appropriately. With auto-compile enabled, after you change the servlet source and save it in a specified directory, the OC4J server automatically compiles and redeploys the servlet the next time it is invoked.
See "Element Descriptions for global-web-application.xml and orion-web.xml" for more information about development
and source-directory
.
Assuming the OC4J server is up and running, by default you can invoke the servlet and see its output from a Web browser as follows, where <
host
>
is the name of the host that the OC4J server is running on, and <
port
>
is the Web listener port:
http://<host><:port>/servlet/HelloWorldServlet
If you are developing in an OC4J standalone environment, use port 8888 to access the OC4J Web listener directly.
This example assumes that "/
" is the context path of the Web application, as is true by default in OC4J standalone for an application deployed to the default Web application.
See "Servlet Invocation" for general information about invoking servlets in OC4J in various situations and environments.
|
![]() Copyright © 2002 Oracle Corporation. All Rights Reserved. |
|