Skip Headers

Oracle Application Server Containers for J2EE Servlet Developer's Guide
10g (9.0.4)

Part Number B10321-01
Go To Documentation Library
Home
Go To Table Of Contents
Contents
Go To Index
Index

Go to previous page Go to next page

2
Servlet Development

This chapter, consisting of the following sections, provides basic information for developing servlets for OC4J and the Oracle Application Server. The first section highlights the use of the standalone version of OC4J for convenience during your development and testing phases.

OC4J Standalone for Development

This manual assumes you are using an OC4J standalone environment for at least your initial development phases. This term refers to the use of a single OC4J instance outside of the Oracle Application Server environment and Oracle Enterprise Manager. Using OC4J standalone is typically more convenient for early development.

The following sections provide some overview and key considerations:

To obtain OC4J standalone, download the oc4j_extended.zip file from the Oracle Technology Network (OTN) at the following location:

http://otn.oracle.com/tech/java/oc4j/content.html


Notes:

  • To use OC4J standalone, you must have a supported version of the Sun Microsystems JDK installed. A JDK is not provided with the OC4J standalone product.

  • During development, also consider the Oracle JDeveloper visual development tool for development and deployment. This tool offers a number of conveniences, as described in "Oracle JDeveloper Support for Servlet Development".


Overview: Using OC4J Standalone

You can start, manage, and control standalone OC4J instances through oc4j.jar (the OC4J standalone executable) and the admin.jar command-line utility, provided with the standalone product. Deploying an EAR file and binding its Web module through admin.jar result in automatic updates to key configuration files.


Note:

Key aspects of the admin.jar utility are covered in Chapter 5, "Deployment and Configuration Overview", particularly in "Deploying an EAR File to OC4J Standalone". For further information, see the Oracle Application Server Containers for J2EE Stand Alone User's Guide.


During testing, it is also possible to manually install an EAR file or individual files according to the J2EE directory structure, and to complete the process by manually updating key configuration files, which triggers OC4J to unpack and deploy the application.

If you have an independent Web application, you can deploy it as a WAR file (or as a directory structure) within the OC4J default J2EE application, rather than using an EAR file.

In addition, for a convenient testing mode, you can deploy individual servlets or JSP pages to the OC4J default Web application.

An OC4J standalone environment, by default, includes the following key directories:

In the simplest case, deploying a test servlet to the OC4J default Web application consists of placing the class file under the /WEB-INF/classes directory under the default Web application root directory.

More detailed deployment considerations, primarily targeting OC4J standalone users, are discussed in Chapter 5. See the following sections in particular:

Also, for information about invoking a servlet in OC4J standalone, see "Servlet Invocation in an OC4J Standalone Environment".

For detailed information about admin.jar and about how to start, stop, configure, and manage your standalone process, download the Oracle Application Server Containers for J2EE Stand Alone User's Guide along with OC4J_extended.zip.

Key OC4J Flags for Development

There are several OC4J flags to be aware of during your development stages, presumably while using OC4J standalone. Note that these flags work independently of each other.


Important:

The check-for-updates flag is used only in OC4J standalone. It is disregarded in an Oracle Application Server environment, where the Oracle Process Management and Notification system (OPMN) and Distributed Configuration Management subsystem (DCM) manage the OC4J file update facilities.



Important:

If you want to re-enable checking after it had been disabled, you must use the admin.jar -updateConfig option after setting check-for-udpates="true", so that OC4J notices this change. After that, automatic checking will be enabled again.


Removal of tools.jar from OC4J Standalone

The OC4J 9.0.3 standalone implementation provided the tools.jar file from the Sun Microsystems JDK 1.3.1. This file includes the java front-end executable and javac compiler executable, for example, among many other components.

The OC4J 9.0.4 standalone implementation no longer provides tools.jar, for a variety of logistical reasons. Therefore, it is required that you install a supported JDK before installing OC4J. The supported JDK versions for the OC4J 9.0.4 implementation are JDK 1.3.1 and JDK 1.4. Oracle Application Server 10g (9.0.4) includes JDK 1.4, so you would likely want to use this JDK version for OC4J standalone as well. However, there are migration issues to consider, particularly the JDK 1.4 requirement that all invoked classes must be in packages. See "JDK 1.4 Considerations: Cannot Invoke Classes Not in Packages".


Note:

OC4J standalone uses javac from the same directory where java is accessed when you start with the "java -jar oc4j.jar" command, ensuring use of the appropriate javac version.


Servlet Development Basics and Key Considerations

Most HTTP servlets follow a standard form. They are written as public classes that extend the HttpServlet class. A servlet overrides the init() and destroy() methods when code is required for initialization work at the time the servlet is loaded by the container, or for finalization work when the container shuts down the servlet. Most servlets override either the doGet() method or the doPost() method of HttpServlet, to handle HTTP GET or POST requests appropriately. These two methods take request and response objects as parameters.

This chapter provides sample servlets that are more advanced than the HelloWorldServlet in "A First Servlet Example".

The following sections cover features and issues to consider before developing your applications:

Sample Code Template

Here is a sample code template for servlet development:

public class myServlet extends HttpServlet {
  
  public void init(ServletConfig config) {
  }

  public void destroy() {
  }

  public void doGet(HttpServletRequest request, HttpServletResponse)
                    throws ServletException, IOException {
  }

  public void doPost(HttpServletRequest request, HttpServletResponse)
                    throws ServletException, IOException {
  }

  public String getServletInfo() {
    return "Some information about the servlet.";
  }

You can optionally override the init(), destroy(), and getServletInfo() methods, but the simplest servlet just overrides either doGet() or doPost().

The reason for overriding the init() method would be to perform special actions that are required only once in the servlet lifetime, such as the following:

Servlet Lifecycle

Servlets have a predictable and manageable lifecycle:

Servlet Preloading

Typically, the servlet container instantiates and loads a servlet class when it is first requested. However, you can arrange the preloading of servlets through settings in the server.xml file, the Web site XML file (such as default-web-site.xml or http-web-site.xml), and the web.xml file. Preloaded servlets are loaded and initialized when the OC4J server starts up or when the Web application is deployed or redeployed.

Preloading requires the following steps:

  1. Verify that the relevant <application> element in the server.xml file has the attribute setting auto-start="true". OC4J inserts this setting by default when you deploy an application.

  2. Specify the attribute setting load-on-startup="true" in the relevant <web-app> subelement of the <web-site> element of the Web site XML file. See "Configuration for Web Site XML Files" for information about the elements and attributes of Web site XML files.

  3. For any servlet you want to preload, there must be a <load-on-startup> subelement under the <servlet> element in the web.xml file for the Web module.

Table 2-1 explains the behavior of the <load-on-startup> element in web.xml.

Table 2-1 File web.xml <load-on-startup> Behavior  
Value Range Behavior

Less than zero (<0)

For example:

<load-on-startup>-1</load-on-startup)

Servlet is not preloaded.

Greater than or equal to zero (>=0)

For example:

<load-on-startup>1</load-on-startup>

Servlet is preloaded. The order of its loading, with respect to other preloaded servlets in the same Web application, is according to the load-on-startup value, lowest number first. (For example, 0 is loaded before 1, which is loaded before 2.)

Empty element

For example:

<load-on-startup/>

The behavior is as if the load-on-startup value is Integer.MAX_VALUE, ensuring that the servlet is loaded after any servlets with load-on-startup values greater than or equal to zero.


Note:

OC4J supports the specification of startup classes and shutdown classes. Startup classes are designated through the <startup-classes> element of the server.xml file and are called immediately after OC4J initializes. Shutdown classes are designated through the <shutdown-classes> element of server.xml and are called immediately before OC4J terminates.

Be aware that startup classes are called before any preloaded servlets.

See the Oracle Application Server Containers for J2EE User's Guide for information about startup classes and shutdown classes.


Servlet Classloading and Application Redeployment

The following sections describe OC4J features and some important considerations regarding servlet classloading and application loading:

OC4J Web Application Redeployment and Class Reloading Features

In OC4J, any of the following circumstances, depending on OC4J polling, will result in redeployment of a Web application and, upon request, reloading of servlet classes and any dependency classes.


Notes:

  • "OC4J polling" refers to the automatic checking of library JAR files and XML configuration files by the OC4J task manager for updates. In an Oracle Application Server environment, this is controlled by OPMN and DCM. In OC4J standalone, it is controlled by the server.xml check-for-updates flag (set to "true" by default), described in "Key OC4J Flags for Development".

  • In this discussion, "redeployment" of a Web application refers to the process where OC4J removes the Web application from its execution space, removes the classloader that was associated with execution of the Web application, reparses web.xml and orion-web.xml, and reinitializes servlet listeners, filters, and mappings.



Note:

Changing a servlet class file in a directory location specified in a <classpath> element in global-web-application.xml or orion-web.xml has the same effect as changing a servlet class file in /WEB-INF/classes. However, changing a JAR file or dependency class file (such as for a JavaBean) in a <classpath> location has no effect.


Be aware of the following important considerations:


Note:

Changing a JAR or ZIP file that is specified in a <library> element, or that is in a directory specified in a <library> element, does not by itself result in redeployment of any Web applications or reloading of classes. The OC4J task manager does not poll these shared library locations.


Loading WAR File Classes Before System Classes in OC4J

The servlet specification recommends, but does not require, loading local classes, which are classes in the WAR file, before system classes, which are any other classes in the environment. Note that "classes in the WAR file" might include classes from the WAR file manifest classpath. By default, the OC4J servlet container does not load local classes first, but this is configurable through the <web-app-class-loader> element in global-web-application.xml or orion-web.xml. This element has two attributes:


Notes:

  • If both attributes are set to "true", the overall classpath is constructed so that classes physically residing in the WAR file are loaded prior to any classes from the WAR file manifest classpath. So you can assume that in the event of any conflict, classes physically residing in the WAR file would take precedence.

  • In accordance with the servlet specification, search-local-classes-first functionality cannot be used in loading classes in java.* or javax.* packages.


Also see "Element Descriptions for global-web-application.xml and orion-web.xml".

Sharing Cached Java Objects Across OC4J Servlets in Oracle Application Server

In order to take advantage of the distributed functionality of the Oracle Application Server Java Object Cache, or to share a cached object between servlets, some minor modification to an application deployment is necessary. Any user-defined objects that will be shared between servlets or distributed between JVMs must be loaded by the system classloader; however, by default, objects loaded by a servlet are loaded by the context classloader. Objects loaded by the context classloader are visible only to the servlets within the servlet context corresponding to that classloader. The object definition would not be available to other servlets or to the cache in another JVM. If an object is loaded by the system classloader, however, the object definition will be available to other servlets and to the cache on other JVMs.

With OC4J, the system classpath is derived from the manifest of the oc4j.jar file and any associated .jar files, including cache.jar. The classpath in the environment is ignored. To include a cached object in the classpath for OC4J, do one of the following with the .class file, assuming an Oracle Application Server environment:

Both the classes directory and the share.jar file are included in the manifest for cache.jar, and are therefore included in the system classpath.

For information about the Oracle Application Server Java Object Cache, see the Oracle Application Server Containers for J2EE Services Guide.

Servlet Information Exchange

A servlet typically receives information from one or more sources, including the following:

The servlet adds information to the response object; the container sends the response back to the client.

Servlet Includes and Forwards

Many servlets use other servlets in the course of their processing, either by "including" another servlet or "forwarding" to another servlet.

In servlet terminology, a servlet include is the process by which a servlet includes response from another servlet within its own response. Processing and response are initially handled by the originating servlet, then are turned over to the included servlet, then revert back to the originating servlet once the included servlet is finished.

With a servlet forward, processing is handled by the originating servlet up to the point of the forward call, at which point the response is reset and the target servlet takes over processing of the request. When a response is reset, any HTTP header settings and any information in the output stream are cleared from the response. After a forward, the originating servlet must not attempt to set headers or write to the response. Also note that if the response has already been committed, then a servlet cannot forward to or include another servlet.

In order to forward to or include another servlet, you must obtain a request dispatcher for that servlet using either of the following servlet context methods:

For getRequestDispatcher(), input the path of the target servlet. For getNamedDispatcher(), input the name of the target servlet, according to the <servlet-name> element for that servlet in the web.xml file.

In either case, the returned object is an instance of a class that implements the javax.servlet.RequestDispatcher interface. (Such a class is provided by the servlet container.) The request dispatcher is a wrapper for the target servlet. In general, the duty of a request dispatcher is to serve as an intermediary in routing requests to the resource that it wraps.

A request dispatcher has the following methods to effect any includes or forwards:

As you can see, you pass in your request and response objects when you call these methods.


Notes:

  • When a servlet forwards to or includes another servlet, default OC4J functionality is to enforce web.xml security constraints on the target servlet as well as the originating servlet. This does not comply with the servlet specification, but you can disable this behavior through the <authenticate-on-dispatch> element in global-web-application.xml or orion-web.xml. See "Element Descriptions for global-web-application.xml and orion-web.xml" for information about this element.

  • When a servlet forwards to or includes another servlet, the default behavior is that any filters that apply to the originating servlet are not executed on the target servlet, but this behavior is configurable. See "Filtering of Forward or Include Targets".


Servlet Thread Models and Related Considerations

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

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. Shared resources fall into two main areas:

One option is to synchronize the service() method as a whole; however, this might adversely affect performance.

A better approach is to selectively protect instance or class fields, or access to external resources, through synchronization blocks.

As perhaps a last resort, the servlet 2.3 specification supports a single-thread model. If a servlet implements the javax.servlet.SingleThreadModel interface, the servlet container must guarantee that there is never more than one request thread at a time in the service() method of any instance of the servlet. This is typically accomplished by creating a pool of servlet instances, with a separate instance handling each concurrent request. This has significant performance impact on the servlet container, however, and should be avoided if at all possible. Furthermore, the SingleThreadModel interface is expected to be deprecated in the servlet 2.4 specification.

For general information about multithreading, see the Sun Microsystems Java Tutorial on Multithreaded Programming at the following Web site:

http://java.sun.com/Series/Tutorial/java/threads/multithreaded.html

Servlet Performance and Monitoring

The following sections list servlet performance considerations and introduce the Oracle Application Server Dynamic Monitoring Service (DMS):

For general OC4J performance information, including coverage of DMS and the dmstool for performance metrics, refer to the Oracle Application Server 10g Performance Guide.

General Performance Considerations

This section provides a summary of issues, mostly documented elsewhere in this manual, that might impact performance:

Oracle Application Server Dynamic Monitoring Service

In an Oracle Application Server environment, DMS adds performance-monitoring features to a number of components, including OC4J. The goal of DMS is to provide information about runtime behavior through built-in performance measurements so that users can diagnose, analyze, and debug any performance problems. DMS provides this information in a package that can be used at any time, including during live deployment. Data are published through HTTP and can be viewed with a browser.

There is standard configuration for the DMS servlets, such as the spy servlet and monitoring agent, in the global application.xml file and the default-web-site.xml file.

In the OC4J application.xml file, the Web modules dms and dms0 and the paths to their WAR files are specified. The default-web-site.xml file specifies that these Web modules are deployed to the OC4J default application and binds them to their context paths. Do not directly alter any of these DMS configurations.

Use the Oracle Enterprise Manager to access DMS, display DMS information, and, if appropriate, alter DMS configuration.

JDK 1.4 Considerations: Cannot Invoke Classes Not in Packages

Among the migration considerations in moving to a Sun Microsystems JDK 1.4 environment, which is the environment that is shipped with Oracle Application Server 10g (9.0.4), there is one of particular importance to servlet and JSP developers.

As stated by Sun Microsystems, "The compiler now rejects import statements that import a type from the unnamed namespace." This was to address security concerns and ambiguities with previous JDK versions. Essentially, this means that you cannot invoke a class (a method of a class) that is not within a package. Any attempt to do so will result in a fatal error at compilation time.

This especially affects JSP developers who invoke JavaBeans from their JSP pages, as such beans are often outside of any package (although the JSP 2.0 specification now requires beans to be within packages, in order to satisfy the new compiler requirements). Where JavaBeans outside of packages are invoked, JSP applications that were built and executed in an OC4J 9.0.3 / JDK 1.3.1 environment will no longer work in an OC4J 9.0.4 / JDK 1.4 environment.

Until you update your application so that all JavaBeans and other invoked classes are within packages, you have the alternative of reverting back to a JDK 1.3.1 environment to avoid this issue.


Notes:

  • The javac -source compiler option is intended to allow JDK 1.3.1 code to be processed seamlessly by the JDK 1.4 compiler, but this option does not account for the "classes not in packages" issue.

  • Only the JDK 1.3.1 and JDK 1.4 compilers are supported and certified by OC4J. It is possible to specify an alternative compiler by adding a <java-compiler> element to the server.xml file, and this might provide a workaround for the "classes not in packages" issue, but no other compilers are certified or supported by Oracle for use with OC4J. (Furthermore, do not update the server.xml file directly in an Oracle Application Server environment. Use the Oracle Enterprise Manager.)


For more information about the "classes not in packages" issue and other JDK 1.4 compatibility issues, refer to the following Web site:

http://java.sun.com/j2se/1.4/compatibility.html

In particular, click the link "Incompatibilities Between Java 2 Platform, Standard Edition, v1.4.0 and v1.3".

Additional Oracle Features

The followings section discuss additional features, mostly Oracle-specific, to consider in developing and running servlets in OC4J:

OC4J Logging

The following sections provide an overview of OC4J logging features:


Note:

Logging features discussed here are for log messages from the OC4J server. It is also possible to use open source frameworks and utilities with OC4J, such as those from the Apache Jakarta Project. This includes log4j, a complementary technology that you can use to insert log statements in your own code. See "Configuration and Use of Jakarta log4j in OC4J".


OC4J Logs

A number of logs are available in OC4J. Because they are not specific to servlets, they are documented elsewhere, but this section provides a summary list and appropriate cross-references. For each log, you have the option of using text-based logging or ODL logging. (See the next section, "Oracle Diagnostic Logging Versus Text-Based Logging".) Note that for ODL, log file names always take the form logN.xml, where N is an integer. For text-based logging, you specify the log file names.

For each log, there is a configuration element (in the appropriate OC4J configuration file) to enable text-based logging, and a separate element to enable ODL logging. The presence of a logging configuration element is what enables the associated type of logging.

OC4J supports the following logs:


Note:

For Web site accessing logging, you can use only one type of logging, not both.


Configuration of the Web access log is covered in this manual. Under "Element Descriptions for Web Site XML Files", see the information about the <access-log> and <odl-access-log> subelements of the <web-site> element.

The Oracle Application Server Containers for J2EE User's Guide has information about how to enable logging to the other OC4J files.

Oracle Diagnostic Logging Versus Text-Based Logging

For each of the logs listed in the preceding section, "OC4J Logs", you have the option of using Oracle Diagnostic Logging (ODL), which offers a some advantages over text-based logging.

ODL provides standardized logging across all components of OC4J, creating the log files in an XML format that can be loaded to a repository for reporting and viewing. You can view ODL logs from Oracle Enterprise Manager, for example.

With ODL, it is also easier to manage the size and number of your log files. In many situations, text-based logging results in the need to periodically shut down the OC4J server and manually clean up the files.

To configure ODL logging for the Web site access log file, use the <odl-access-log> subelement of the <web-site> element in the Web site XML file. To use text-based logging, use the <access-log> subelement of the <web-site> element instead.

For each of the other OC4J logs, use the <odl> subelement of the <log> element in the appropriate XML configuration file if you want to use ODL logging. To use text-based logging, use the <file> subelement of the <log> element instead.


Note:

Web site access logs commonly use standard XLF or CLF format (extended log file format or common log file format). Users can split the files according to a specified time period, such as time of day or day of month. ODL Web site logs, however, do not support XLF or CLF format and you cannot split files by time period. When you reach the maximum size of an ODL log file, a new file is automatically created. (Log file names are log1.xml, log2.xml, and so on.)


See the Oracle Application Server Containers for J2EE User's Guide for additional information about ODL.

Additional Oracle Application Server Log Files

In an Oracle Application Server environment, in addition to the OC4J log files discussed previously, there is support for the following log files:

OPMN manages Oracle HTTP Server and OC4J processes within an application server instance. For information about this, refer to the Oracle Application Server 10g Administrator's Guide.

Servlet Debugging

This discussion summarizes debugging features and considerations for servlet developers, with appropriate cross-references for additional information. It consists of the following sections:

OC4J Debugging Flags

OC4J supports a number of flags to enable debugging output for various subsystems.

For HTTP debugging:

For AJP debugging (for Oracle Application Server with Oracle HTTP Server only):

The AJP flags do not produce user-friendly output, but are necessary for debugging some AJP issues.

For JDBC debugging:

For EJB debugging:

For RMI debugging:

For Web services debugging:

Setting OC4J Debugging Flags

The debugging flags are enabled through Java option settings such as the following:

-Dhttp.session.debug=true

If you are using OC4J standalone, this would be on the Java command line when you start OC4J. In an Oracle Application Server environment, use Oracle Enterprise Manager. This would be in the Java Options field under Command Line Options in the Application Server Control Server Properties Page for the OC4J instance. To get to this page, select Server Properties under Instance Properties in the Administration Page for the OC4J instance. See "Application Server Control OC4J Administration Page". See the Oracle Application Server Containers for J2EE User's Guide for further information.

Timing Considerations for Debugging in Oracle Application Server

Due to how OPMN functions, there are timing issues to consider when debugging in an Oracle Application Server environment. Specifically, whenever debugging results in the halting of a process, OPMN will terminate that process once the halt goes beyond the timeout period.

To remedy this situation, you must set an appropriate timeout value, using the <timeout> element in the opmn.xml file.

For information about opmn.xml, refer to the Oracle Application Server 10g Administrator's Guide.

Debugging through JDeveloper and Other IDEs

If you use Oracle JDeveloper as your development environment, you can take advantage of its debugging features.

For debugging, JDeveloper offers local and remote debugging of JSP pages, servlets, and other Java source files. You can start by setting breakpoints in the source files within JDeveloper and running a debugging session with the source selected. While debugging an application such as a servlet in JDeveloper, you have complete control over the execution flow and can view and modify variable values as well as perform advanced application performance monitoring such as viewing class instance counts and memory usage. JDeveloper will follow calls from your application into other source files or offer to generate stub classes for class sources that are not available. Remote debugging, once the code to be debugged is launched and the JDeveloper debugger is attached to it, is very similar to local debugging.

See "Oracle JDeveloper Support for Servlet Development" for a general summary of JDeveloper features for servlet development.


Note:

Other key IDE vendors have built plug-in modules that allow seamless integration with OC4J. This provides developers with the capability to build, deploy, and debug J2EE applications running on OC4J directly from within the IDE. You can refer to the following Web site for more information:

http://otn.oracle.com/products/ias/9ias_partners.html

(You will need an Oracle Technology Network membership, but they are free of charge.)


Oracle JDeveloper Support for Servlet Development

Visual Java programming tools now typically support servlet coding. In particular, Oracle JDeveloper supports servlet development and includes the following features:

Also see "Debugging through JDeveloper and Other IDEs".

For general information about JDeveloper, refer to the JDeveloper online help or to the following site on the Oracle Technology Network:

http://otn.oracle.com/products/jdev/content.html

Introduction to OC4J Support for Open Source Frameworks

OC4J supports some common open source utilities and frameworks. For Oracle Application Server 10g (9.0.4), this document discusses support for two in particular:

The focus is on configuring and using these open source utilities in the OC4J standalone environment. See Appendix A, "Open Source Frameworks and Utilities".

Servlet Invocation

A servlet is invoked by the container when a request for the servlet arrives from a client. The client request might come from a Web browser or a Java client application, or from another servlet in the application using the request forwarding mechanism, or from a remote object on a server.

A servlet is requested through its URL mapping, as described shortly.

Servlet invocation, including some special OC4J features for invoking a servlet by class name in a development or testing scenario, is covered in the following sections:

Summary of URL Components

Before discussing servlet invocation, it is useful to summarize the components of a URL. Here is the generic construct (though note that pathinfo is usually empty):

protocol://host:port/contextpath/servletpath/pathinfo

You could also have additional information following any delimiters, such as request parameter settings following a question mark ("?") delimiter:

protocol://host:port/contextpath/servletpath/pathinfo?param=value

Table 2-2 describes the components of the generic construct.

Table 2-2 URL Components  
Component Description

Protocol

The network protocol to be used when invoking the Web application. Examples are http, https, ftp, and ormi (for EJBs).

Host

The network name of the server that the Web application is running on. If the Web client is on the same system as the application server, you can use localhost. Otherwise, use the host name (as defined in /etc/hosts on a UNIX system, for example), such as:

www.example.com

Port

The port that the Web server listens on. If a URL does not specify a port, most browsers assume port 80 for HTTP protocol or port 443 for HTTPS.

For OC4J, the port number is specified in the port attribute of the <web-site> element in the Web site XML file, such as default-web-site.xml for an Oracle Application Server environment or http-web-site.xml for OC4J standalone. (For each port, there must be one associated protocol according to the <web-site> element protocol attribute.)

Context path

The designated root path for the servlet context. You specify the context path when you deploy an application. For OC4J, the specified context path is reflected in the setting of the root attribute of the <web-app> element (a subelement of <web-site>) in the Web site XML file.

Each servlet context is associated with a directory path in the server file system.

The <web-app> element also indicates the J2EE application name (and EAR file name) through its application attribute, and the Web module name (and WAR file name) through its name attribute. The J2EE application name, Web module name, and context path are all mapped together in this way. Here is an example:

<web-app application="ojspdemos" name="ojspdemos-web"
         root="/ojspdemos" />

Servlet path

The designated path, beyond the context path, for the particular servlet you want to invoke. You specify the servlet path through standard mappings in the application web.xml file. A servlet class is mapped to an arbitrary servlet name through <servlet-class> and <servlet-name> subelements of a <servlet> element. The servlet name is mapped to a servlet path through <servlet-name> and <url-pattern> subelements of a <servlet-mapping> element. (You can map a single servlet class to multiple servlet names and multiple servlet paths.) Here is an example:

<web-app>
  ...
  <servlet>
    <servlet-name>logout</servlet-name> 
    <servlet-class>
       oracle.security.jazn.samples.http.Logout
    </servlet-class> 
  </servlet>
  ...
  <servlet-mapping>
    <servlet-name>logout</servlet-name> 
    <url-pattern>/logout/*</url-pattern> 
  </servlet-mapping>
  ...
</web-app>

Path information

(This is typically empty.) Beyond the context path and servlet path, a URL can contain additional information that is supplied to the servlet through the HTTP request object. Such information is presumably understood by the servlet. This information is separate from any request parameter settings or other URL components that follow delimiters such as question marks. Such delimiters would follow any path information.


Note:

The name specified in a <servlet-name> element is the name you would input to the servlet context getNamedDispatcher() method if you want a request dispatcher for that servlet.


For more information about the OC4J configuration elements and attributes discussed in the table, see "Element Descriptions for Web Site XML Files". For information about elements and attributes of the web.xml file, see the Sun Microsystems Java Servlet Specification.

Consider the following sample URL:

http://www.example.com:8888/foo/bar/mypath/MyServlet/info1/info2?user=Amy

In the process of invoking a servlet according to a URL supplied by a client browser, the servlet container takes the following steps:

  1. It examines everything in the URL after the port number, then examines its own configuration settings (such as in a Web site XML file) for recognized context paths, then determines what part of the URL is the context path.

    Assume for this example that /foo/bar is the context path.

  2. It examines everything in the URL after the context path, then examines the servlet mappings in the web.xml file for recognized servlet paths, then determines what part of the URL is the servlet path.

    At this point, the servlet can be invoked. The servlet container does not use any information beyond the servlet path.

    Assume for this example that /mypath/MyServlet is the servlet path.

  3. If anything remains in the URL after the servlet path and preceding any URL delimiters (such as "?" in this example, which delimits request parameter settings), that portion of the URL is taken as extra information and is passed to the servlet through the HTTP request object.

    Assume for this example that /info1/info2 is the extra path information.

It is important to realize that the context path, servlet path, and any path information can all be "compound" components, with one or more forward-slashes in between parts. This is shown in the preceding example. In many cases, the context path might be simple, such as just foo, and the servlet path might also be simple, such as just MyServlet, and any path information might be simple as well. But it is impossible to know by just looking at a URL what part of it is the context path, what part is the servlet path, and what part is extra path information (if any). You must examine the configuration in the Web site XML file and web.xml file to determine this.


Notes:

  • See the Oracle Application Server Containers for J2EE User's Guide or Oracle Application Server Containers for J2EE Stand Alone User's Guide for information about defined ports and what listeners they are mapped to, and for information about how to alter these settings.

  • Cookie names are based on the host name, port number, and path (just the context path by default, but possibly including the servlet path as well).

  • The concepts of servlet contexts and context paths were introduced in the servlet 2.2 specification. Apache JServ, for example, preceded this specification and has no such concepts.

  • You can retrieve the context path, servlet path, and path information through the getContextPath(), getServletPath(), and getPathInfo() methods of the HTTP request object.


Servlet Invocation by Class Name During OC4J Development

For a development or testing scenario in OC4J, there is a convenience mechanism for invoking a servlet by class name. For security reasons, the presumption is that you would use this mechanism only while developing your application.

The servlet-webdir attribute in the <orion-web-app> element of the global-web-application.xml file or orion-web.xml file defines a special URL component that is used to invoke servlets by class name. This URL component follows the context path in the URL, and anything following this URL component is assumed to be a servlet class name, including applicable package information, within the appropriate servlet context. The servlet class name appears instead of a servlet path in the URL. (Technically, the servlet-webdir value is the servlet path and acts as a servlet itself, and the class name of the servlet you wish to execute is taken as path information.)

Generally speaking, for any given application, OC4J behavior for invocation by class name is determined by the servlet-webdir setting in the orion-web.xml file for that application, if there is a setting. But note the following:

For information about OC4J system properties, see the Oracle Application Server Containers for J2EE Stand Alone User's Guide, or the Oracle Application Server Containers for J2EE User's Guide for an Oracle Application Server environment. See the Oracle Application Server 10g Release Notes for your platform for information about the default value of the http.webdir.enable system property and any default setting of servlet-webdir in the global-web-application.xml file that is shipped with OC4J.

The following URL invokes a servlet called SessionServlet by its class name, assuming a setting of servlet-webdir="/servlet/". In this example, assume SessionServlet is in package foo.bar and executes in the OC4J default Web application. Also assume a context path of "/" (the default for the default Web application in OC4J standalone).

http://www.example.com:8888/servlet/foo.bar.SessionServlet

This mechanism applies to any servlet context, however, and not just for the default Web application. If the context path is foo, for example, the URL to invoke by class name would be as follows:

http://www.example.com:8888/foo/servlet/foo.bar.SessionServlet


Important:

Allowing the invocation of servlets by class name presents a significant security risk; OC4J should not be configured to operate in this mode in a production environment. See "Additional Security Considerations" for information.


Servlet Invocation in an Oracle Application Server Production Environment

The following sections describe Oracle HTTP Server and OC4J features for servlet invocation in an Oracle Application Server Environment:

Key Features for Invocation in Oracle Application Server

In an Oracle Application Server production environment, OC4J should always be accessed through the Oracle HTTP Server. Oracle HTTP Server uses AJP (Apache JServ protocol) to communicate to OC4J, but this is invisible to the end user.

When a servlet is requested, the OC4J servlet container interprets the URL as described in "Summary of URL Components".

Whatever port number is used would be mapped to AJP protocol through a <web-site> element in the default-web-site.xml file. (This is the typical name, but Web site XML file names are according to settings in the server.xml file and can be changed as desired.) This is through the port and protocol attributes of the <web-site> element, with port set as desired and protocol set to "ajp13". By default, as the product is currently shipped, port 7777 is for access through the Oracle HTTP Server with Oracle Application Server Web Cache enabled.

Whenever you use Enterprise Manager to deploy an application, you are prompted for a URL mapping, which will result in a new OC4J mount point in mod_oc4j.conf. If you specify a URL mapping of "/mypath", for example, this is the context path of your Web application and is defined as a new OC4J mount point. Then you would invoke a servlet with a URL such as the following:

http://www.example.com:7777/mypath/MyServlet

See "Application Server Control Deploy Application (EAR) Page" and "Application Server Control Deploy Web Application (WAR) Page" for information about the Enterprise Manager EAR and WAR deployment pages.

For an overview of deployment to Oracle Application Server, see "OC4J Deployment in Oracle Application Server". For further information, see the Oracle Application Server Containers for J2EE User's Guide. For general information about Enterprise Manager, see Oracle Enterprise Manager Concepts.

See the Oracle HTTP Server Administrator's Guide for information about Oracle HTTP Server configuration, mount points, and the mod_oc4j.conf file.

Use of Perceived Front-End Hosts by OC4J

There is an additional element in the default-web-site.xml file (or other Web site XML file) that is relevant in servlet invocation. The <frontend> subelement of the <web-site> element can specify a perceived front-end host and port of the Web site as seen by HTTP clients. When the site is behind a load balancer or firewall, the <frontend> specification is necessary to provide appropriate information to the Web application for functionality such as URL rewriting. Attributes are host, for the name of the front-end server (such as "www.example.com"), and port, for the port number of the front-end server (such as "8080"). Using this front-end information, the back-end server that is actually running the application knows to refer to www.example.com instead of to itself in any URL rewriting. This way, subsequent requests properly come in through the front-end again, instead of trying to access the back-end directly.

The specified front-end host and port settings are also reflected back to the servlet and are the values you receive if you call the getServerName() or getServerPort() method of the HTTP request object.

Servlet Invocation in an OC4J Standalone Environment

In OC4J standalone, a Web site uses HTTP protocol without going through the Oracle HTTP Server and AJP, and is configured according to settings in the http-web-site.xml file. (This is the typical name, but Web site XML file names are according to settings in the server.xml file and can be changed as desired.)

When a servlet is requested, the OC4J servlet container interprets the URL as described in "Summary of URL Components".

Whatever port number is used would be mapped to HTTP protocol through a <web-site> element in the http-web-site.xml file (or other Web site XML file, as applicable). This is through the port and protocol attributes of the <web-site> element, with port set as desired and protocol set to "http". By default (as currently shipped), port 8888 is for direct access to OC4J through its own Web listener.

In OC4J standalone, the default context path is "/" to use HTTP protocol for an application that is deployed to the OC4J default Web application. Here is an example:

http://www.example.com:8888/MyServlet

If you are not using the default Web application, specify the context path while deploying the application. You can either do this through the admin.jar utility, or by manual deployment and manual edits of the http-web-site.xml file (not generally recommended). Deployment for OC4J standalone is discussed in "Deployment Scenarios to OC4J Standalone", but for complete information see the Oracle Application Server Containers for J2EE Stand Alone User's Guide. That document also has information about OC4J port settings and other default settings.

If you specify "/mypath" as the context path, for example, you would invoke the servlet with a URL such as the following:

http://www.example.com:7777/mypath/MyServlet

Servlet Sessions

Servlet sessions were introduced in "Introduction to Servlet Sessions". The following sections provide details and examples:

Session Tracking

This section provides an overview of servlet session tracking and features, then describes the OC4J implementation.

Overview of Session Tracking

The HTTP protocol is stateless by design. This is fine for stateless servlets that simply take a request, do a few computations, output some results, and then in effect go away. But many, if not 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 involves identifying user sessions by ID numbers and tying requests to their session through use of the ID number. The typical mechanisms for this are cookies or URL rewriting.

The OC4J servlet container, in accordance with the servlet specification, implements session tracking through HTTP session objects, which are instances of a class that implements the javax.servlet.http.HttpSession interface.

When a servlet creates an HTTP session object (through the request object getSession() method), the client interaction is considered to be stateful.

An HTTP session object has scope over the Web application only. You cannot use session objects to share data between applications. Nor can you use session objects to share data between different clients of the same application. There is one HTTP session object for each client in each application.


Note:

To share information between clients or applications, you can store such persistent data in a database if you need the protection, transactional safety, and backup that a database offers. Alternatively, you can save persistent information on a file system or in a remote object.


Cookies

A number of approaches have been used in attempting to add a measure of statefulness to the HTTP protocol. The most widely accepted is the use of cookies, used to transmit an identifier between server and client, in conjunction with stateful servlets that can maintain session objects. Session objects are simply dictionaries that store values (Java objects) together with their associated keys (Java strings).

Cookie usage is as follows:

  1. With the first response from a stateful servlet after a session is created, the server (container) sends a cookie with a session identifier back to the client, often along with a small amount of other useful information (all less than 4 KB). The container sends the cookie, named JSESSIONID, in the HTTP response header.

  2. Upon each subsequent request from the same Web client session (assuming the client supports cookies), the client sends the cookie back to the server as part of the request, and the cookie value is used by the server to look up session state information to pass to the servlet.

  3. With subsequent responses, the container sends the updated cookie back to the client.

The servlet code is not required to do anything to send a cookie; this is handled by the container. Sending cookies back to the server is handled automatically by the Web browser, unless the user disables cookies.

The container uses the cookie for session maintenance. A servlet can retrieve cookies using the getCookies() method of the HttpServletRequest object, and can examine cookie attributes using the accessor methods of the javax.servlet.http.Cookie objects.

URL Rewriting

An alternative to using cookies is URL rewriting, through the encodeURL() method of the response object. This is where the session ID is encoded into the URL path of a request. See "Session Servlet Example" for an example of URL rewriting.

The name of the path parameter is jsessionid, as in the following example:

http://host:port/myapp/index.html?jsessionid=6789

Similarly to the functionality of cookies, the value of the rewritten URL is used by the server to look up session state information to pass to the servlet.

Although cookies are typically enabled, the only way for you to ensure session tracking is to use encodeURL() in your servlets, or encodeRedirectURL() for redirects.


Note:

In accordance with the servlet specification, calls to the encodeURL() and encodeRedirectURL() methods will result in no action if cookies are enabled.


Other Session Tracking Methods

Other techniques have been used in the past to relate client and server sessions, including server hidden form fields and user authentication mechanisms to store additional information. Oracle does not recommend these techniques in OC4J applications. They have many drawbacks, including performance penalties and loss of confidentiality.

Session Tracking in OC4J

For session-tracking in OC4J, the servlet container will first attempt to accomplish tracking through cookies. If cookies are disabled, session tracking can be maintained only by using the encodeURL() method of the response object, or the encodeRedirectURL() method for redirects. You must include the encodeURL() or encodeRedirectURL() calls in your servlet if cookies might be disabled.

The use of session cookies is disabled by the following setting in the global-web-application.xml or orion-web.xml file:

<session-tracking cookies="disabled" ... >
   ...
</session-tracking>

Cookies are enabled by default.


Notes:

  • OC4J does not support auto-encoding, where session IDs are automatically encoded into the URL by the servlet container. This is a non-standard and expensive process.

  • An encodeURL() or encodeRedirectURL() call will not encode the session ID into the URL if the cookie mechanism is found to be working properly.

  • The encodeURL() method replaces the servlet 2.0 encodeUrl() method (note capitalization), which is deprecated.


Features of the HttpSession Interface

As noted earlier, the servlet container uses HTTP session objects--instances of a class that implements the javax.servlet.http.HttpSession interface--in tracking and managing user sessions. The HttpSession interface specifies the following public methods to get and set session information:

Depending on the configuration of the servlet container and the servlet itself, sessions might expire automatically after a set amount of time or might be invalidated explicitly by the servlet. Servlets can manage session lifecycle with the following methods, specified by the HttpSession interface:

For an example of how a servlet can use an HTTP session object, see "Session Servlet Example".

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

Session Cancellation

HTTP session objects persist for the duration of the server-side session. A session is either terminated explicitly by the servlet or it "times out" after a certain period and is cancelled by the container.

Cancellation Through a Timeout

The default session timeout for the OC4J server is 20 minutes. You can change this for a specific application by setting the <session-timeout> subelement under the <session-config> element of web.xml. Specify the timeout in minutes, as an integer. For example, to reduce the session timeout to five minutes, add the following lines to the application web.xml file:

<session-config>
  <session-timeout>5</session-timeout>
</session-config>

According to the servlet specification, a negative value specifies the default behavior that a session never times out. For example:

<session-config>
  <session-timeout>-1</session-timeout>
</session-config>

A value of 0 results in an immediate timeout.

Cancellation by the Servlet

A servlet explicitly cancels a session by invoking the invalidate() method on the session object. You must obtain a new session object by invoking the getSession() method of the HttpServletRequest object.

Session Replication in a Distributable Application

The session object of a stateful servlet can be replicated to other OC4J servers in a load-balanced cluster island. If the server handling a request to a servlet should fail, the request can "failover" to another JVM on another server in the cluster island and the session state will still be available.

The following sections provide more information:

Overview of Session Replication and Requirements

To enable replication of the session state of an application between OC4J servers, you must mark the Web application as distributable, by use of the standard <distributable> element in the web.xml file. The presence of this subelement of the <web-app> element, as follows, specifies that the application is distributable:

<web-app ... >
   ...
   <distributable/>
   ...
</web-app>


Note:

In an Oracle Application Server environment, accomplish this through Oracle Enterprise Manager. See the discussion of clustering in the Oracle Application Server Containers for J2EE User's Guide for details.


Objects that are stored by a servlet in the HttpSession object are replicated. They must be serializable (directly or indirectly implementing the java.io.Serializable interface) or remoteable (directly or indirectly implementing the java.rmi.Remote interface) for replication to work properly. Furthermore, any objects that are referenced by objects in the session object must themselves be serializable or remoteable.

Possible Clustering Error Conditions and Related Environment Flags

Replicated data is sent asynchronously to the other OC4J servers in the cluster island. For performance reasons, OC4J does not wait to confirm successful replication. It is therefore possible, though highly unlikely, that either of the following error scenarios would occur.

Because of the possible error scenarios, OC4J and Oracle HTTP Server maintain session affinity, meaning they make every effort to always route requests and responses through the same OC4J JVM. The session cookie, JSESSIONID, maintains the required, detailed routing information across HTTP requests to ensure that subsequent requests through Oracle HTTP Server are dispatched to the originating JVM wherever possible.

In addition, the OC4J 9.0.4 implementation introduces two environment flags that you can use to reduce the risk of either error scenario occurring:

Session Replication Details and Logistics

For a distributable application, session replication is triggered each time there is a setAttribute() call on the session object. The name and value specified in the call are serialized and replicated, with the serialized value being stored using the specified name as the key. The value is deserialized only upon first access by a failed-over servlet.

Be aware that you must explicitly call setAttribute() whenever you update a data item belonging to the session object. For example, if you call getAttribute() on the session object to retrieve a bean, then call a method on the bean to change its state, you must then call setAttribute() on the session object to update the bean in the session. This is in contrast to the situation in a non-distributable environment, where the bean is passed to you by reference and updated directly within the session object as soon as you call the method on the bean.

Also be aware of the performance implications of this functionality. A servlet with a large number of setAttribute() calls might have lower performance due to the small overhead introduced when performing state replication.


Note:

You can observe the runtime status of replication and session state updates by enabling the OC4J debugging flags http.session.debug and http.cluster.debug. See "OC4J Debugging Flags" and "Setting OC4J Debugging Flags".


Session Servlet Example

The SessionServlet code below implements a servlet that establishes an HttpSession object and prints data held by the request and session objects.

SessionServlet Code

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Date;

public class SessionServlet extends HttpServlet { 

  public void doGet (HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

    // Get the session object. Create a new one if it doesn't exist.
    HttpSession session = req.getSession(true);

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    out.println("<head><title> " + "SessionServlet Output " +
                "</title></head><body>");
    out.println("<h1> SessionServlet Output </h1>");
    // Set up a session hit counter. "sessionservlet.counter" is just the
    // conventional way to create a key for the value to be stored in the
    // session object "dictionary".
    Integer ival = 
      (Integer) session.getAttribute("sessionservlet.counter");
    if (ival == null) {
      ival = new Integer(1);
    }
    else {
      ival = new Integer(ival.intValue() + 1);
    }

    // Save the counter value.
    session.setAttribute("sessionservlet.counter", ival);

    // Report the counter value. 
    out.println(" You have hit this page <b>" + 
                ival + "</b> times.<p>");

    // This statement provides a target that the user can click
    // to activate URL rewriting. It is not done by default.
    out.println("Click <a href=" + 
                res.encodeURL(HttpUtils.getRequestURL(req).toString()) + 
                ">here</a>");
    out.println(" to ensure that session tracking is working even " +
                "if cookies aren't supported.<br>");
    out.println("Note that by default URL rewriting is not enabled" +
                " due to its large overhead.");

    // Report data from request.
    out.println("<h3>Request and Session Data</h3>");
    out.println("Session ID in Request: " +
                req.getRequestedSessionId());
    out.println("<br>Session ID in Request is from a Cookie: " +
                req.isRequestedSessionIdFromCookie());
    out.println("<br>Session ID in Request is from the URL: " +
                req.isRequestedSessionIdFromURL());
    out.println("<br>Valid Session ID: " +
                req.isRequestedSessionIdValid());

    // Report data from the session object.
    out.println("<h3>Session Data</h3>");
    out.println("New Session: " + session.isNew());
    out.println("<br> Session ID: " + session.getId());
    out.println("<br> Creation Time: " + new Date(session.getCreationTime()));
    out.println("<br>Last Accessed Time: " +
                new Date(session.getLastAccessedTime()));

    out.println("</body>");
    out.close();
  }

  public String getServletInfo() {
    return "A simple session servlet";
  }
}

Deploying and Testing

In OC4J standalone, save the preceding code into a file SessionServlet.java in the OC4J default Web application /WEB-INF/classes directory. By default, the default Web application root directory is j2ee/home/default-web-app. (See "OC4J Default Application and Default Web Application" for more information.)

For convenience, use the development="true" setting in the <orion-web-app> element of the global-web-application.xml file. See "Element Descriptions for global-web-application.xml and orion-web.xml" for more information about the development flag.

Figure 2-1 shows the output of this servlet when it is invoked the second time in a session by a Web browser that has cookies enabled. Experiment with different Web browser settings--for example, by disabling cookies--then select the HREF that causes URL rewriting.

Figure 2-1 Session Servlet Display

Text description of sessserv.gif follows.

Text description of the illustration sessserv.gif

Servlet Security

OC4J supports Secure Socket Layer (SSL) communication between Oracle HTTP Server and OC4J in an Oracle Application Server environment, using secure AJP. This is the secure version of Apache JServ Protocol, the protocol used by Oracle HTTP Server to communicate with OC4J. The following sections go into appropriate detail:

This discussion is followed by a section of general security considerations:


Notes:

  • Secure communication between a client and Oracle HTTP Server is independent of secure communication between Oracle HTTP Server and OC4J. (Also note that the secure AJP protocol used between Oracle HTTP Server and OC4J is not visible to the end user.) This section covers only secure communication between Oracle HTTP Server and OC4J.

  • In addition, OC4J standalone supports SSL communication directly between a client and OC4J, using HTTPS. See the Oracle Application Server Containers for J2EE Stand Alone User's Guide, available when you download the standalone version from OTN.


See the following documents for additional information about Oracle Application Server security and Oracle HTTP Server.

Use of Security Features

The following sections discuss how to use SSL features with OC4J and Oracle HTTP Server:

Using Certificates with OC4J and Oracle HTTP Server

The steps below are for using keys and certificates for SSL communication in OC4J. These are server-level steps, typically executed prior to deployment of an application that will require secure communication, perhaps when you first set up an Oracle Application Server instance.

Note that a keystore is used to store certificates, including the certificates of all trusted parties, for use by a program. Through its keystore, an entity such as OC4J (for example) can authenticate other parties as well as authenticate itself to other parties. Oracle HTTP Server uses what is called a wallet for the same purpose.

In Java, a keystore is a java.security.KeyStore instance that you can create and manipulate using the keytool utility that is provided with the Sun Microsystems JDK. The underlying physical manifestation of this object is a file. Go to the following site for information about keytool:

http://java.sun.com/j2se/1.3/docs/tooldocs/win32/keytool.html

The Oracle Wallet Manager has functionality for Oracle wallets that is equivalent to the functionality of keytool for keystores.

Here are the steps in using certificates between OC4J and Oracle HTTP Server:

  1. Use keytool to generate a private key, public key, and unsigned certificate.You can place this information into either a new keystore or an existing keystore.

  2. Obtain a signature for the certificate, using either of the following two approaches.

    You can generate your own signature:

    1. Use keytool to "self-sign" the certificate. This is appropriate if your clients will trust you as, in effect, your own certificate authority.

    Alternatively, you can obtain a signature from a recognized certificate authority:

    1. Using the certificate from Step 1, use keytool to generate a certificate request, which is a request to have the certificate signed by a certificate authority.

    2. Submit the certificate request to a certificate authority.

    3. Receive the signature from the certificate authority and import it into the keystore, again using keytool. In the keystore, the signature will be matched with the associated certificate.


Note:

Oracle Application Server includes Oracle Application Server Certificate Authority (OCA). This allows customers to create and issue certificates for themselves and their users, although these certificates would likely be unrecognized outside a customer's organization without prior arrangements. See the Oracle Application Server Certificate Authority Administrator's Guide for information about OCA.


The process for requesting and receiving signatures is up to the particular certificate authority you use. Because that is outside the scope and control of Oracle Application Server, the Oracle Application Server documentation does not cover it. You can go to the Web site of any certificate authority for information. (Any browser should have a list of trusted certificate authorities.) Here are the Web addresses for VeriSign, Inc. and Thawte, Inc., for example:

http://www.verisign.com/

http://www.thawte.com/

For SSL communication between OC4J and Oracle HTTP Server, you would also execute the preceding steps for Oracle HTTP Server, but using a wallet and Oracle Wallet Manager instead of a keystore and the keytool utility. See the Oracle Application Server 10g Security Guide for information about wallets and the Oracle Wallet Manager.

In addition to steps 1 and 2 above, execute steps 3 and 4 as necessary:

  1. If the OC4J certificate is signed by an entity that Oracle HTTP Server does not yet trust, obtain the certificate of the entity and import it into Oracle HTTP Server. The specifics depend on whether the OC4J certificate in question is self-signed, as follows.

    If OC4J has a self-signed certificate (essentially, Oracle HTTP Server does not yet trust OC4J):

    1. From OC4J, use keytool to export the OC4J certificate. This places the certificate into a file that is accessible to Oracle HTTP Server.

    2. From Oracle HTTP Server, use Oracle Wallet Manager to import the OC4J certificate.

    Alternatively, if OC4J has a certificate that is signed by another entity (that Oracle HTTP Server does not yet trust):

    1. Obtain the certificate of the entity in any appropriate way, such as by exporting it from the entity. The exact steps vary widely, depending on the entity.

    2. From Oracle HTTP Server, use Oracle Wallet Manager to import the certificate of the entity.

  2. If the Oracle HTTP Server certificate is signed by an entity that OC4J does not yet trust, and OC4J is in a mode of operation that requires client authentication (as discussed in "Requesting Client Authentication"), then obtain the certificate of the entity in any appropriate way, such as by exporting it from the entity. The exact steps vary widely, depending on the entity. From OC4J, use keytool to import the certificate of the entity.

    
    


Note:

During communications over SSL between Oracle HTTP Server and OC4J, all data on the communications channel between the two is encrypted. The following steps are executed: 1) The OC4J certificate chain is authenticated to Oracle HTTP Server during establishment of the encrypted channel. 2) Optionally, if OC4J is in client-authentication mode, Oracle HTTP Server is authenticated to OC4J. This also occurs during establishment of the encrypted channel. 3) Any further communication after this initial exchange will be encrypted.


Example: Creating an SSL Certificate and Generating Your Own Signature

This example corresponds to Step 2 above, in the mode where you generate your own signature by using keytool to self-sign the certificate.

First, create a keystore with an RSA private/public keypair, using the keytool command. The following example (in which % is the system prompt) uses the RSA keypair algorithm to generate a keystore to reside in a file named mykeystore, which has a password of 123456 and is valid for 21 days:

% keytool -genkey -keyalg "RSA" -keystore mykeystore -storepass 123456 -validity 21

Note the following:

The keytool prompts you for more information, as follows:

What is your first and last name?
  [Unknown]:  Test User
What is the name of your organizational unit?
  [Unknown]:  Support
What is the name of your organization?
  [Unknown]:  Oracle
What is the name of your City or Locality?
  [Unknown]:  Redwood Shores
What is the name of your State or Province?
  [Unknown]:  CA
What is the two-letter country code for this unit?
  [Unknown]:  US
Is <CN=Test User, OU=Support, O=Oracle, L=Reading, ST=Berkshire, C=GB> correct?
  [no]:  yes

Enter key password for <mykey>
        (RETURN if same as keystore password):


Note:

To determine your two-letter country code, use the ISO country code list at the following URL:

 http://www.bcpl.net/~jspath/isocodes.html.

The mykeystore file is created in the current directory. The default alias of the key is mykey.

Requesting Client Authentication

OC4J supports a client authentication mode in which the server explicitly requests authentication from the client before the server will communicate with the client. In an Oracle Application Server environment, Oracle HTTP Server acts as the client to OC4J.

For client authentication, Oracle HTTP Server must have its own certificate and authenticates itself by sending a certificate and a certificate chain that ends with a root certificate. OC4J can be configured to accept only root certificates from a specified list in establishing a chain of trust back to a client.

A certificate that OC4J trusts is called a trust point. In the certificate chain from Oracle HTTP Server, the trust point is the first certificate that OC4J encounters that matches one in its own keystore. There are three ways to establish trust:

OC4J verifies that the entire certificate chain up to and including the trust point is valid to prevent any forged certificates.

If you request client authentication with the needs-client-auth attribute, perform the following steps. See "OC4J Configuration Steps for SSL" for how to configure this attribute.

  1. Decide which of the certificates in the chain from Oracle HTTP Server is to be your trust point. Ensure that you either have control over the issuance of certificates using this trust point or that you trust the certificate authority as an issuer.

  2. Import the intermediate or root certificate in the server keystore as a trust point for authentication of the client certificate.


Note:

If you do not want OC4J to accept certain trust points, make sure these trust points are not in the keystore.


  1. Execute the steps to create the client certificate (documented in "Using Certificates with OC4J and Oracle HTTP Server"). The client certificate includes the intermediate or root certificate that is installed in the server. If you wish to trust another certificate authority, obtain a certificate from that authority.

  2. Save the certificate in a file on Oracle HTTP Server.

  3. Provide the certificate for the Oracle HTTP Server initiation of the secure AJP connection.

Configuration of Oracle HTTP Server and OC4J for SSL

For secure communication between Oracle HTTP Server and OC4J, configuration steps are required at each end, as detailed in the following sections:

Oracle HTTP Server Configuration Steps for SSL

In Oracle HTTP Server, verify proper SSL settings in mod_oc4j.conf for secure communication. SSL must be enabled, with a wallet file and password specified, as follows:

Oc4jEnableSSL on
Oc4jSSLWalletFile wallet_path
Oc4jSSLWalletPassword pwd

The wallet_path value is a directory path to the wallet file, without a file name. (The wallet file name is already known.) The pwd value is the wallet password.

For more information about the mod_oc4j.conf file, see Oracle HTTP Server Administrator's Guide.

OC4J Configuration Steps for SSL

In the default-web-site.xml file (or other Web site XML file, as appropriate), you must specify appropriate SSL settings under the <web-site> element.

  1. Turn on the secure flag to specify secure communication, as follows:

    <web-site ... secure="true" ... >
       ...
    </web-site>
    
    

    Setting secure="true" specifies that the AJP protocol should use an SSL socket.

  2. Use the <ssl-config> subelement and its keystore and keystore-password attributes to specify the path and password for the keystore, as follows:

    <web-site ... secure="true" ... >
       ...
       <ssl-config keystore="path_and_file" keystore-password="pwd" />
    </web-site>
    
    

    The <ssl-config> element is required whenever the secure flag is set to "true".

    The path_and_file value can indicate either an absolute or relative directory path and includes the file name. A relative path is relative to the location of the Web site XML file.

  3. Optionally, to specify that client authentication is required, turn on the needs-client-auth flag. This is an attribute of the <ssl-config> element.

    <web-site ... secure="true" ... >
       ...
       <ssl-config keystore="path_and_file" keystore-password="pwd" 
                   needs-client-auth="true" />
    </web-site>
    
    

    This sets up a mode where OC4J will accept or reject a client entity, such as Oracle HTTP Server, for secure communication depending on its identity. The needs-client-auth flag instructs OC4J to request the client certificate chain upon connection. If OC4J recognizes the root certificate of the client, then the client is accepted.

    The keystore that is specified in the <ssl-config> element must contain the certificates of any clients that are authorized to connect to OC4J through secure AJP and SSL.

Here is an example that sets up secure communication with client authentication:

<web-site display-name="OC4J Web Site" protocol="ajp13" secure="true" >
   <default-web-app application="default" name="defaultWebApp" root="/j2ee" />
   <access-log path="../log/default-web-access.log" />
   <ssl-config keystore="../keystore" keystore-password="welcome" 
              needs-client-auth="true" />
</web-site>

Only the portions in bold are specific to security. The protocol value is always "ajp13" for communication through Oracle HTTP Server, whether or not you use secure communication. A protocol value of ajp13 with secure="false" indicates AJP protocol, while ajp13 with secure="true" indicates secure AJP protocol.

For more information about elements and attributes of the <web-site> and <ssl-config> elements, see "Element Descriptions for Web Site XML Files".

Also see "Requesting Client Authentication" for related information.

SSL Common Problems and Solutions

This section discusses some common SSL errors and their causes and remedies, followed by a brief discussion of general SSL debugging.

SSL Common Errors

The following errors may occur when using SSL certificates:

Keytool Error: java.security.cert.CertificateException: Unsupported encoding

Cause: There is trailing white space, which the keytool utility does not allow.

Action: Delete all trailing white space. If the error still occurs, add a newline in your certificate reply file.

Keytool Error: KeyPairGenerator not available

Cause: You are probably using the keytool utility from an older JDK.

Action: Use the keytool utility from the latest JDK on your system. To ensure that you are using the latest JDK, specify the full path for this JDK.

Keytool Error: Failed to establish chain from reply

Cause: The keytool utility cannot locate the root CA certificates in your keystore, so cannot build the certificate chain from your server key to the trusted root certificate authority.

Action: Execute the following:

keytool -keystore keystore -import -alias cacert -file cacert.cer (keytool 
-keystore keystore -import -alias intercert -file inter.cer) 

If you use an intermediate CA keytool utility, then execute the following:

keystore keystore -genkey -keyalg RSA -alias serverkey keytool -keystore 
keystore -certreq -file my.host.com.csr 

Get the certificate from the Certificate Signing Request (CSR), then execute the following:

keytool -keystore keystore -import -file my.host.com.cer -alias serverkey

No available certificate corresponds to the SSL cipher suites that are enabled

Cause: Something is wrong with your certificate.

Action: Determine and rectify the problem.

General SSL debugging

While you are developing in OC4J standalone, you can display verbose debug information from the Java Secure Socket Extension (JSSE) implementation. To get a list of options, start OC4J as follows:

java -Djavax.net.debug=help -jar oc4j.jar 

Start it as follows to enable full verbosity:

java -Djavax.net.debug=all -jar oc4j.jar

This will display the browser request header, server HTTP header, server HTTP body, content length (before and after encryption), and SSL version.

Additional Security Considerations

In addition to the SSL functionality discussed previously, there are several considerations regarding the security of your Web application running in the OC4J servlet container:


Go to previous page Go to next page
Oracle
Copyright © 2002, 2003 Oracle Corporation.

All Rights Reserved.
Go To Documentation Library
Home
Go To Table Of Contents
Contents
Go To Index
Index