Configuring orion-web.xml

Configuring orion-web .xml

Now that you've mastered application deployment, you can move ahead and explore more OC4J features.

With the right global settings, many J2EE web application archives (EAR files) can be deployed unchanged, without any special configuration beyond their standard web.xml descriptors. However, if you want to take advantages of OC4J features, you need to add an OC4J-specific descriptor, orion-web.xml , located at /WEB-INF/orion-web.xml , to the web module.

Tip 

Any orion-web.xml settings not specified for an individual application will inherit values from the global-web-application.xml configuration file in the orahome/j2ee/<instance- name >/config directory, which uses the same DTD as orion-web.xml .

The orion-web.xml deployment descriptor does the following:

  • Configures reloading behavior, charsets, and other web container settings.

  • Allows overriding of context parameters and environment entries in web.xml .

  • Configures web application classloading behavior.

  • Configures file types and virtual hosts .

  • Configures clustering for this web application (if clustered).

  • Configures additional Servlet filters.

  • Configures the sessions used to store data for users connected to the web application.

  • Resolves resources (including JDBC data sources, EJBs, JMS destinations and connection factories, and JavaMail sessions) to specific services deployed in OC4J.

  • Resolves security roles to users or groups defined by the configured UserManager or Java Authorization (JAZN) realm.

  • Configures host and IP-based network access controls.

  • Allows overriding of any element in web.xml .

The document type declaration (DTD) used for the orion-web.xml deployment descriptor and the global-web-application.xml configuration file can be found on Oracle's website at http://xmlns.oracle.com/ias/dtds/orion-web-9_04.dtd .

First Look at orion-web.xml

Now that you know what this descriptor does, you can add it to the project. You'll start off with the most basic orion-web.xml , as shown in the following listing:

 <?xml version="1.0"?> <!DOCTYPE orion-web-app PUBLIC "-//ORACLE//DTD OC4J Web Application 9.04//EN"   "http://xmlns.oracle.com/ias/dtds/orion-web-9_04.dtd"> <orion-web-app     deployment-version="9.0.4.0.0"     temporary-directory="./temp"     internationalize-resources="false"     default-mime-type="application/octet-stream"> </orion-web-app> 

When you rebuild, repackage, and redeploy the application, nothing notable is going to happen. The Servlet is still going to print Foobar , and the JSP pages will be compiled as usual. Let's take a look at the full orion-web-app element in the orion-web.xml file.

 <?xml version="1.0"?> <!DOCTYPE orion-web-app PUBLIC "-//ORACLE//DTD OC4J Web Application 9.04//EN" "http://xmlns.oracle.com/ias/dtds/orion-web-9_04.dtd"> <orion-web-app     deployment-version="9.0.4.0.0"     temporary-directory="./temp"     internationalize-resources="false"     default-mime-type="application/octet-stream"     default-buffer-size="2048"     default-charset="iso-8859-1"     source-directory="/WEB-INF/src"     simple-jsp-mapping="true"     servlet-webdir="/sample"     persistence-path="./temp"     jsp-timeout="100"     jsp-taglib-locations="/WEB-INF"     jsp-print-null="true"     jsp-cache-tlds="true"     jsp-cache-directory="./temp"     file-modification-check-interval="20000"     enable-jsp-dispatcher-shortcut="true"     directory-browsing="allow"     development="true"> </orion-web-app> 

Before you move any further let's examine each attribute in more detail. Even though the attributes and their values are fairly self-explanatory, there are a few candidates for a more detailed description, as shown in Table 10-2.

Table 10-2: orion-web-app Element Attributes

Attribute

Description

deployment-version

Default deployment version should be set to 9.0.4.0.0 for 10g application server.

temporary-directory

Directory the server is going to use for temporary files, such as JSP Servlets. The current directory is orahome/j2ee/<instance-name>/application-deployments/<application-name>/<web-module-name> , so ./temp in the home instance maps to orahome/j2ee/home/application-deployments/sample/sample/temp .

internationalize-resources

Specifies whether to load resources based on the server's locale.

default-mime-type

Sets the default mime type for the application.

default-buffer-size

Sets the size of the output stream buffer.

default-charset

Specifies the default character set for the application.

source-directory

Used in conjunction with development="true" ; specifies the source directory, and that the files in the source directory will automatically be recompiled when they're changed.

simple-jsp-mapping

If set to true, OC4J will use oracle.jsp.runtimev2.JspServlet to compile the JSP pages. This will speed up JSP processing, but if you're using Servlets that map to *.jsp URL pattern, you must set this to false.

servlet-webdir

Specifies the Servlet runner path for invoking a Servlet by class name. Anything appearing after this path in a URL is assumed to be a class name, including the package as appropriate.

persistence-path

Specifies directory to persist session state between redeployments. If this value isn't specified, application state will be lost between redeployments. Note that all objects must be marked by Serializable interface.

jsp-timeout

Sets the timeout after which the JSP page will be removed from memory. This is useful when you have limited resources and want to free up as much memory as possible. Setting timeout to 0 means no timeout; any positive value means a timeout in seconds.

jsp-print-null

If set to true, OC4J will print null for JSP pages that don't generate any content.

jsp-cache-directory

The JSP cache directory is used as a base directory for output files from the JSP translator. It's also used as a base directory for application-level TLD caching. The default value is ./persistence , relative to the deployment directory of the application.

jsp-cache-tlds

Specifies whether to cache tag library definition files.

jsp-taglib-locations

If jsp-cache-tlds is set to true, you can specify the location of well-known TLD files in a semicolon-separated list. The location list can include JAR files.

file-modification-check-interval

Sets interval in which the static files (such as images or HTML files) are checked for modification, in milliseconds . It's advisable to set this to a very high value in production environment.

enable-jsp-dispatcher-shortcut

If your JSP files use numerous include statements, you can improve performance by setting this to true. You can gain further performance boost by setting this attribute to true together with simple-jsp-mapping .

directory-browsing

Specifies whether users are allowed to view the directory structure of your application.

development

Specifies that this application is in the development phase and OC4J will detect changes to files in path defined in source-directory and recompile them. However, this means that your source-directory must match the structure of the application, which is generally not a good practice.

Now that you know what attributes you can set in the root element of the orion-web.xml descriptor, you can move on to all the other settings you can use to modify the behavior of OC4J and the application.

Overriding Context Parameters and Environment Variables

Every application will sooner or later have to be changed. Providing that all you need to do to accomplish the change request is to change the configuration file, OC4J allows you to modify the application's settings without changing the original web.xml descriptor. This can be price-less, because you can keep the original web.xml in the source control and still be able to tweak the application's configuration on production servers, by overriding values in this web.xml descriptor from the orion-web.xml descriptor.

The following elements in orion-web.xml can override individual context parameters and environment entries defined in web.xml (located in the /WEB-INF directory of the web module), as shown in Table 10-3.

Table 10-3: context-param-mapping Element of the orion-web.xml Descriptor

Parameter

Description

context-param-mapping

Overrides a context parameter, replacing the value specified in web.xml with the value specified in the body of this element.

context-param-mapping:name

The name of the context-param to override (should match the name in web.xml ).

env-entry-mapping

Overrides the value of an environment entry specified in web.xml .

env-entry-mapping:name

The name of the env-entry to override (should match the name in web.xml ).

Let's take a look at a practical example that will show how to override values defined in the web.xml file. You'll start with a standard web.xml descriptor, where you'll define a context-param value, as follows :

 <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"       "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app>     <display-name>OC4J Sample Web Application</display-name>     <description>Chapter 10 sample application</description>  <context-param>   <param-name>publisher</param-name>   <param-value>CHANGE-ME</param-value>   <description>Publisher of the book</description>   </context-param>  <!-- etc --> </web-app> 

Ideally, you would still like to keep the web.xml descriptor clean of all deployment-specific settings. This is where orion-web.xml comes in place. You can use the context-param-mapping element and override the appropriate context parameter, as shown in the following code sample:

 <?xml version="1.0"?> <!DOCTYPE orion-web-app PUBLIC "-//ORACLE//DTD OC4J Web Application 9.04//EN" "http://xmlns.oracle.com/ias/dtds/orion-web-9_04.dtd"> <orion-web-app>     <context-param-mapping name="publisher">         <![CDATA[  Apress  ]]>     </context-param-mapping> </orion-web-app> 

Finally, to see that it actually works, you'll modify the Servlet to read in the context parameter and to print to the response stream, as follows:

 public class SampleServlet extends HttpServlet {     protected void doGet(HttpServletRequest request, HttpServletResponse response)         throws ServletException, IOException {  Object publisher = getServletContext().getInitParameter("publisher");  response.getOutputStream().print("Foobar, published by " + publisher);     }     protected void doPost(HttpServletRequest request, HttpServletResponse response)         throws ServletException, IOException {         doGet(request, response);     } } 

After redeploying the application and navigating to http://localhost/sample/foo.html , you'll see something like Foobar, published by Apress .

You can use the same procedure to override environment settings in web.xml , from orion-web.xml .

Classloading

The elements described in this section allow for the customization of classloading behavior for a particular web application. This can be useful for backward compatibility and for resolving a variety of classpath issues. In particular, if a library that dynamically loads classes is used at a higher level in the classloading hierarchy, then setting the search-local-classes-first option may be the only way to avoid classloading issues, without placing the entire web application codebase at the higher level.

Note 

See Chapter 3 for a review of the mechanics of Java classloading.

The issues with classloading are particularly important when you have more than one application in the container, and each application uses different versions of individual classes. You must configure the container's class loader for each application separately so that it will not try to make its job easier by using an already-loaded class or interface.

Consider a situation in which you have two applications that use the same class, but in which each application uses a different version of the class. This isn't too difficult to imagine if you have to support legacy applications. If you placed the JAR containing the class into the applib directory so that the applications can share it then the classloader would ignore classes in the application's lib directory. You can use orion-web.xml to specify classloader settings for each application in an instance, using the following two elements: classpath and web-app-class-loader , which are explained in Table 10-4.

Table 10-4: Classloading Mappings

Parameter

Description

Default Value

classpath

Specifies an additional codebase that should be placed on the classpath for this web application.

 

classpath:path

The path to the codebase (either absolute or relative to orion-web.xml ).

 

web-app-class-loader

Allows configuration of web application classloading behavior (through the two attributes listed next ).

 

web-app-class-loader:search-local-classes-first

If true, the server will load classes from the WAR in preference to those found higher in the classloader hierarchy (that is, a class located in WEB-INF/someLib.jar would be loaded instead of one on the system classpath).

false

web-app-class-loader:include-war-manifest-class-path

If true, the server will honor the classpath specified in the WAR's manifest file. If false, that classpath with be ignored.

true

To try classloading out, you'll create a simple JAR library with a single class, called ClassloaderTester . You'll place the JAR in the orahome/j2ee/<instance-name>/applib directory and use it in the application. Then you'll modify the ClassloaderTester code, place it in the application's lib directory and run the application again. You'll follow this process in detail to demonstrate and test the classloading functionality of OC4J.

To do this, you'll need to modify the project's directory structure and the build file. The modification to the directory structure is quite straightforward: You'll add util/src/java, util/build and util/dist directories to the project. You need to add these two directories because you'll want to build a JAR file with classes from util/src/java .

The additions to the build file aren't too complex, either. All you need to do is to compile the source files in util/src/java and package them into util.jar in util/dist , as shown in the following code sample:

Modified /build.xml file

 <project name="sample" basedir="." default="dist-ear">     <!-- configure the basic directory properties -->     <!-- build directories as usual -->  <property name="dir.util.java.src" value="util/src/java"/>   <property name="dir.util.build" value="util/build"/>   <property name="dir.util.dist" value="util/dist"/>  <!-- Create needed directories -->     <target name="init">         <mkdir dir="${dir.dist}"/>         <mkdir dir="${dir.web.build}"/>         <mkdir dir="${dir.web.dist}"/>  <mkdir dir="${dir.util.build}"/>   <mkdir dir="${dir.util.dist}"/>  </target>     <!-- Compile the sources -->     <target name="compile-web" depends="init, compile-util">         <javac srcdir="${dir.web.java.src}" destdir="${dir.web.build}"             debug="on" debuglevel="lines,vars,source">             <classpath refid="project.classpath"/>  <classpath path="${dir.util.build}"/>  <exclude name="**/Test*.java"/>             <exclude name="**/AllTests.java"/>         </javac>     </target>     <target name="compile-util" depends="init">         <javac srcdir="${dir.util.java.src}" destdir="${dir.util.build}"             debug="on" debuglevel="lines,vars,source">             <classpath refid="project.classpath"/>             <exclude name="**/Test*.java"/>             <exclude name="**/AllTests.java"/>         </javac>     </target>  <target name="dist-util" depends="compile-util">   <jar destfile="${dir.util.dist}/util.jar">   <fileset dir="${dir.util.build}">   <include name="**/*.class"/>   </fileset>   </jar>   </target>  <target name="dist-web" depends="compile-web, dist-util">         <delete file="${dir.dist}/sample.war"/>         <war warfile="${dir.web.dist}/sample.war"             webxml="${dir.web.as-web.src}/WEB-INF/web.xml" >             <classes dir="${dir.web.build}">                 <include name="**/*.class"/>             </classes>             <lib dir="${dir.lib}" includes="*.jar"/>  <lib dir="${dir.util.dist}" includes="*.jar"/>  <fileset dir="${dir.web.as-web.src}">             <!-- etc -->         </war>     </target>     <!-- etc --> </project> 

Before you can demonstrate classloading settings, you have to actually use the code from util.jar in the application, as follows:

 public class SampleServlet extends HttpServlet {     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {         Object publisher = getServletContext().getInitParameter("publisher");         ClassloaderTester tester = new ClassloaderTester();         response.getOutputStream().print("Foobar, published by " + publisher + ",             version " + tester.getVersion());     }     protected void doPost(HttpServletRequest request, HttpServletResponse response)         throws ServletException, IOException {         doGet(request, response);     } } 

When you deploy the application and navigate to http://localhost/sample/foo.html , you'll see Foobar, published by Apress, version v1 . This proves that the Servlet can load the ClassloaderTester class from util.jar , which is in turn placed in the web application's lib directory.

Let's now modify the build file further to move the util.jar library out of the lib directory of the web application and place it into orahome/j2ee/<instance-name>/applib . To do that, simply remove the <lib dir="${dir.util.dist}" includes="*.jar"/> line from the <war> element in the dist-web target in the build.xml file, and copy util.jar to the applib directory of the instance you're using and restart the instance. Running the application again will produce the same output.

Let's now modify the ClassloaderTester class to return a different value, say v2 , and place it back into the lib directory of the application. When you redeploy the application, it will still print Foobar, published by Apress, version v1 , because the classloader loaded ClassloaderTester class from util.jar in the applib directory.

In order to correct this, modify the orion-web.xml descriptor in /src/web/as-web/WEB-INF , as shown here:

 <?xml version="1.0"?> <!DOCTYPE orion-web-app PUBLIC "-//ORACLE//DTD OC4J Web Application 9.04//EN" "http://xmlns.oracle.com/ias/dtds/orion-web-9_04.dtd"> <orion-web-app> <!-- everything else unchanged -->  <web-app-class-loader   search-local-classes-first="true"   include-war-manifest-class-path="true" />  </orion-web-app> 

Rebuild and redeploy the application and it prints Foobar, published by Apress, version v2 , even though ClassloaderTester class in util.jar in applib still returns v1 .

Classpath Settings

Sometimes it's necessary to directly modify the classpath that OC4J is to use for the application. To do this, all you need to specify is the <classpath> element after the root element, as shown here:

 <?xml version="1.0"?> <!DOCTYPE orion-web-app PUBLIC "-//ORACLE//DTD OC4J Web Application 9.04//EN" "http://xmlns.oracle.com/ias/dtds/orion-web-9_04.dtd"> <orion-web-app>  <classpath path="./lib/util.jar"/>  </orion-web-app> 

File Types, Locations, and Type-Based Filters

OC4J sets the MIME type on a response based on file-extension mappings found in a mime-mappings file. However, in some cases, you may want to intercept certain types of files (for example, XML) and transform them before they're returned to the client. The Servlet-chaining element allows you to configure a Servlet to intercept outgoing responses of a certain MIME type.

At other times, you may want requests for certain files to be mapped to a common shared directory on the server. Using the <virtual-directory> element, you can map a "virtual" directory within the web application to a real directory somewhere on the server. This can often be useful for sharing large repositories of static content between applications, as shown in Table 10-5.

Table 10-5: MIME Mappings and Servlet Chaining

Parameter

Description

Default Value

mime-mappings

References the file that contains extension to mime-type mappings.

 

mime-mappings:path

Either an absolute path to the mime-mappings file, or a path relative to orion-web.xml .

./mime.types

virtual-directory

Specifies the path of a directory on the server that should be mapped to a "virtual" directory within the web application.

 

virtual-directory:real-path

Path of the real directory on the server (for example, /var/sample/static )

 

virtual-directory:virtual-path

Path within the web application that should be used to access it (for example, static/ )

 

servlet-chaining

Specifies a Servlet to be called after a response has been generated with a certain MIME type (but before it's returned to the client).

 

servlet-chaining:mime-type

The MIME type to intercept.

 

servlet-chaining:servlet-name

The Servlet that should be called for the specified MIME type.

 

We'll discuss the servlet-chaining parameter in more detail later in this chapter; the mime-mappings and virtual-directory elements are best demonstrated using an example. Let's consider the following scenario: A client's request is handled by SampleServlet , which sets content type to text/plain depending on a request parameter. The task is to filter the output generated by SampleServlet to make sure it's text/plain . The most elegant way to do this is to implement another Servlet, TextPlainServlet , which will read all input from the request, filter it, and write it to the response. OC4J will take care of chaining the TextPlain-Servlet after SampleServlet . Let's modify SampleServlet and create TextPlainServlet , as follows:

 public class SampleServlet extends HttpServlet {     // doPost omitted     protected void doGet(HttpServletRequest request, HttpServletResponse response)         throws ServletException, IOException {         Object publisher = getServletContext().getInitParameter("publisher");         ClassloaderTester tester = new ClassloaderTester();  if (request.getParameter("plain") != null) {   response.setContentType("text/plain");   }  response.getOutputStream().print("Foobar, published by " + publisher +         ", version " + tester.getVersion());     } } public class TextPlainServlet extends HttpServlet {     protected void doGet(HttpServletRequest request, HttpServletResponse response)         throws ServletException, IOException {         byte[] buffer = new byte[16384];         int read;         while ((read = request.getInputStream().read(buffer, 0, buffer.length)) > 0) {             // do some advanced filtering here  response.getOutputStream().write(buffer, 0, read);  }         response.getOutputStream().print(". Filtered by TextPlainServlet");     }     protected void doPost(HttpServletRequest request, HttpServletResponse response)         throws ServletException, IOException {         doGet(request, response);     } } 

You can see that TextPlainServlet doesn't actually do any processing by itself; it simply transforms input received from the request stream to the response stream. There's actually no filtering in the sample code; we'll leave any transformation of the input to the output to you.

Next, you need to define the TextPlainServlet in web.xml and specify it in orion-web.xml , as follows:

 <web-app>     <!-- etc -->     <servlet>         <servlet-name>samplePlain</servlet-name>         <servlet-class>com.apress.oc4j.webapplications.TextPlainServlet </servlet-class>         <load-on-startup>2</load-on-startup>     </servlet>     <!-- etc --> </web-app> 

Notice that you don't actually map the Servlet to any URL pattern. Next you'll modify the orion-web.xml descriptor so that the TextPlainServlet is executed before the response is returned to the client, as shown here:

 <orion-web-app>     <servlet-chaining mime-type="text/plain" servlet-name="samplePlain"/> </orion-web-app> 

Let's see if the changes worked: Go to http://localhost/sample/foo.html . The output will be Foobar, published by Apress, version v2 , which is exactly what you should be expecting. If you now set the request parameter Plain to any value, the TextPlainServlet will execute the request to http://localhost/sample/foo.html?plain=1 as Foobar, published by Apress, version v2. Filtered by TextPlainServlet .

Virtual Directories

To take a break from all the programming you can take a look at MIME types and virtual directories. Sometimes you'll want to store a lot of static content outside of the web application, but you'll want it to be accessible from the application's context. You may have thousands of images you want to display from your application, but you want to keep them in a separate directory on the server's file system. Creating a virtual directory takes care of this situation, as shown here:

 <orion-web-app>     <virtual-directory real-path="C:\var\oc4j\sample\static"     virtual-path="/static"/> </orion-web-app> 

The content of C:\var\oc4j\sample\static is just one image, as shown in Figure 10-10.

image from book
Figure 10-10: File in C:\var\oc4j\sample\static

Provided that you have added the virtual-directory element to orion-web.xml and redeployed the application, you should see the cover of Oracle Application Server 10g on http://localhost/sample/static/10gASCover.jpg

Clustering

Clustered web applications should specify the following elements listed in Table 10-6 under the <orion-web-app> element in orion-web.xml . Nonclustered applications should omit them. For more about clustering, see Chapter 21.

Table 10-6: Clustering Settings

Parameter

Description

Default Value

cluster-config

Specifies a cluster-id and network information used to share HttpSession state. Should only be used within clustered applications.

 

cluster-config:host

The multicast host or IP to be used for cluster data.

230.0.0.1

cluster-config:id

The cluster identifier for this server instance.

Defaults based on local machine IP address

cluster-config:port

The port to be used for cluster data.

9127

URL-Based Expiration

In many situations, you may want to adapt the application's behavior based on particular URL patterns. For instance, you may use a Servlet filter to detect and prevent data mining, or set a special expiration policy for files that never change.

The <servlet-filter> elements defined in orion-web.xml offer the same functionality as the more portable Servlet filter declarations in web.xml . If a <servlet-filter> with the same name already exists in web.xml , specifying it again in orion-web.xml will override the definition from web.xml . This is useful for specifying additional configuration parameters for the filter. If the filter doesn't exist in web.xml , but does exist in orion-web.xml , the filter will be added. Unlike all other settings defined OC4J descriptor files, settings in web.xml override settings in global-web-application.xml .

The <expiration-setting> element allows you to customize caching behavior for certain request patterns. If your web application uses images generated on the fly, for example, you should to specify 0 for the expires attribute to make sure the users always see the most up-to-date image. The filter settings are listed in Table 10-7.

Table 10-7: Servlet Filter Settings

Parameter

Description

expiration-setting

Allows the customization of cache expirations based on a particular URL pattern.

expiration-setting:expires

The number of seconds before a matching URL should expire ("never" if it should never expire).

expiration-setting:url-pattern

The URL pattern to be matched (for example, *.png ).

The expiration settings are sent to the client; it is therefore up to the client's browser to make another request when the content expires. You may set the content to expire say every hour on all static GIF images by specifying expiration-setting in orion-web.xml :

 <orion-web-app>     <expiration-setting url-pattern="*.gif" expires="60"/> </orion-web-app> 

Session Configuration, Session and Request Tracking

HTTP user sessions are generally managed by a Servlet container through browser cookies. Some users, however, may be unable or unwilling to accept cookies, in which case the server will fall back to URL rewriting, in which every link includes a unique session ID that can be used to locate a user 's session state across requests. URL rewriting adds additional strain (even if very low) to the server, because the server needs to preprocess each request to include and identify the session ID.

The use of this feature depends on the target audience of your application. If you're developing an intranet application, there's no need for URL rewriting because the application is going to run in a controlled environment where you can make sure all client browsers allow cookies. For an application that's required to be accessible to all clients , enabling URL rewriting is necessary. URL rewriting is handled by OC4J; it's transparent to any Java code. You can use request.getSession() and OC4J will make sure that your code will receive a valid HttpServletSession object.

The following elements configure the default session behavior and allow you to specify Servlets to track both sessions and requests. These settings are listed in Table 10-8.

Table 10-8: Session Tracking Settings

Parameter

Description

Default Value

request-tracker

Allows the specification of a Servlet that should be invoked once for each request (for example, to record it to a log).

 

request-tracker:servlet-name

The name of the Servlet to be invoked.

 

session-tracking

Parameters for how the web app tracks sessions.

 

session-tracking:autoencode-absolute-urls

If true and cookies are disabled, causes OC4J to use URL rewriting for session tracking.

false

session-tracking:autoencode-urls

If true and cookies are disabled, causes OC4J to use URL rewriting for session tracking.

false

session-tracking:autojoin-session

If true, users are assigned a session immediately when they log in to the application.

false

session-tracking:cookie-domain

The domain associated with the cookie.

 

session-tracking:cookie-max-age

Maximum number of seconds a cookie should be saved by the browser. If unspecified, the cookie doesn't outlive the user's browser session.

 

session-tracking:cookies

Whether session cookies should be used.

enabled

session-tracker

Allows the specification of a Servlet that should be invoked whenever a session is created (for example, to record it to a log).

 

session-tracker:servlet-name

The name of the Servlet to be invoked.

 

We'll demonstrate both request and session tracking using a very basic Servlet called RequestTrackerServlet . The actual implementation isn't going to do any actual tracking; it will simply remind the user that his request is being tracked, as shown here:

 public class RequestTrackerServlet extends HttpServlet {     protected void doGet(HttpServletRequest request, HttpServletResponse response)         throws ServletException, IOException {  response.getOutputStream().print(   "Long live bytecode!");  }     protected void doPost(HttpServletRequest request, HttpServletResponse response)         throws ServletException, IOException {         doGet(request, response);     } } 

If you add a request-tracker element to orion-web.xml and register the Servlet in web.xml you'll see a dark reminder printed by the RequestTrackerServlet whenever you make a request to the application.

 <web-app>  <servlet>   <servlet-name>requestTrackerServlet</servlet-name>mn   <servlet-class>   com.apress.oc4j.webapplications.RequestTrackerServlet</servlet-class>   </servlet>  </web-app> 

Notice that we didn't specify the load-on-startup priority for the Servlet in the web.xml descriptor to make sure the TrackerServlet doesn't get loaded when the application starts, as shown here:

 <orion-web-app>     <request-tracker servlet-name="requestTrackerServlet"/> </orion-web-app> 

Any requests to the application will now pass through the request Servlet. The tracker Servlet can perform any processing; it doesn't necessarily have to modify the output. Session tracking works in exactly the same way as request tracking. Create a Servlet, define it in web.xml and then instruct OC4J to treat it as session filter Servlet in orion-web.xml .

Session settings on the other hand are very straightforward, and except for a word of warning to use consistent naming scheme for your cookies, there's nothing tricky or difficult about them.

Resolving Resource References and EJB References

Resources and EJBs referenced by the web application (in web.xml ) should be mapped to actual Java Naming and Directory Interface (JNDI) locations using the elements in the following code sample. Let's consider this scenario: In JNDI, you wish to configure a DataSource that you'll use in the web application.

 <orion-web-app>  <resource-ref-mapping location="jdbc/HyperSonicDS" name="jdbc/myDS"/>  </orion-web> 

This instructs OC4J to map an existing JNDI entry into a new one, providing that the value of the name attribute matches a resource-ref element in a web.xml descriptor. These references are listed in Table 10-9. In the following code example, we've mapped jdbc/HyperSonicDS to jdbc/myDS and you can now use this in the application's Java code, as follows:

 Context context=new InitialContext(); DataSource ds=(DataSource)context.lookup("java:comp/env/jdbc/myDS"); 
Table 10-9: EJB References in orion-web.xml

Parameter

Description

resource-ref-mapping

Resolves a reference to a DataSource , JMS destination, mail session, or other resource.

resource-ref-mapping:location

JNDI name where the resource can be found.

resource-ref-mapping:name

Name used in the web.xml reference.

lookup-context

Allows the optional specification of a particular context to be used to look up a resource (useful when the resource is outside the server).

lookup-context:location

Name where resource can be found in the specified context.

context-attribute

Specifies JNDI properties to be used for the specified lookup-context . Only the initial context factory property is required.

context-attribute:name

Name of the JNDI property (for example, java.naming.factory.initial ).

context-attribute:value

Value of the JNDI property (for example, the class name of the initial context factory).

ejb-ref-mapping

Maps an EJB reference to a deployed EJB.

ejb-ref-mapping:location

The JNDI location where the EJB is located.

ejb-ref-mapping:name

The name of the EJB ref in the web.xml reference.

Finally, it's important to realize that these mappings affect only the web application, not necessarily every component within an EAR file.

Security Configuration and Resolving Security Roles

If OC4J can map every application role directly to a group defined in principals.xml with the same names . Then the following security elements aren't necessary. However, for portability, backward compatibility, future security, and other considerations, it's usually more appropriate to explicitly map application roles to actual users and groups using a <security-role-mapping> . Specifying any security-role-mapping s will disable the implicit mappings to principals.xml . The security configuration settings are listed in Table 10-10.

Table 10-10: Security Configuration Settings in orion-web.xml

Parameter

Description

Default Value

security-role-mapping

Maps a J2EE application role to one or more users and groups known to the UserManager .

 

security-role-mapping:impliesAll

If true, all users are assumed to have this role. If false, individual users and groups should be specified using the <user> and <group> elements.

false

security-role-mapping:name

The name of the role as specified in web.xml .

 

user

Allows the assignment of a role to an individual user.

 

user:user:name

The username of the user who should be given this role.

 

group

Allows the assignment of a role to a group of users.

 

group:name

Name of the group that should be given this role.

 

A good place to get thorough understanding of security roles is Chapter 7. Here's a quick example that will show you if a user is in a particular role:

 public class SampleServlet extends HttpServlet {     protected void doGet(HttpServletRequest request, HttpServletResponse response)         throws ServletException, IOException {  Principal principal = request.getUserPrincilal();   if (request.isUserInRole("users")) {  response.getOutputStream().print("Only human!");         } else{             response.getOutputStream().print("The One!");         }         response.getOutputStream().print(principal.getName());     }     protected void doPost(HttpServletRequest request, HttpServletResponse response)         throws ServletException, IOException {         doGet(request, response);     } } 

This simple example demonstrates how to get the Principal of a user accessing the Servlet. If you need to check role membership, you can use the request.isUserInRole() method, however, you shouldn't have to do this because you'll probably use declarative security and access control in the web.xml descriptor, as shown in the following code sample.

Declarative security in web.xml

 <web-app> <!-- -->     <security-constraint>         <web-resource-collection>             <web-resource-name>Admin</web-resource-name>             <url-pattern>/admin/*</url-pattern>         </web-resource-collection>         <auth-constraint>             <role-name>Root</role-name>             <role-name>Administrators</role-name>         </auth-constraint>     </security-constraint>     <security-constraint>         <web-resource-collection>             <web-resource-name>Users</web-resource-name>             <url-pattern>/users/*</url-pattern>         </web-resource-collection>         <auth-constraint>             <role-name>Users</role-name>         </auth-constraint>     </security-constraint> </web-app> 

With these settings in the web.xml descriptor, OC4J will make sure that requests to path /admin/* can be executed only by Root and Administrators , and any requests to /users/* can be allowed from members of the Users role.

Host and Network-Based Access Control

The <access-mask> element can be used to allow or deny individual domains or IP addresses.

If the default attribute is set to allow , then all hosts and IPs will be allowed to access the application except those specifically denied through <host-access> or <ip-access> subelements. If default is set to deny , then only the specifically allowed hosts and IP addresses will be able to access the application.

The access control is checked by the server itself; you don't need to write any Java code to enforce these checks. It's useful to set up this security scheme for internal applications that will be accessed from a limited range of fixed (and trusted) IP addresses. Table 10-11 lists the element attributes.

Table 10-11: access-mask Element Attributes

Parameter

Description

Default Value

access-mask

Allows the restriction of access to particular domains and IP addresses, or the exclusion of particular domains and IP addresses.

 

access-mask:default

Whether unspecified domains and IP addresses should be allowed or denied ( allow deny ).

allow

host-access

Restricts or allows access for a particular domain.

allow

host-access:domain

The host or domain (for example, saturn.wrox.com ).

 

host-access:mode

Whether the corresponding host or domain should be allowed or denied.

 

ip-access

Restricts or allows access for a particular IP address.

 

ip-access:ip

The IP address (for example, 201.33.155.2).

allow

ip-access:mode

Whether the IP address should be allowed or denied.

 

ip-access: netmask

Subnet mask.

 

For example, to only allow requests from saturn.apress.com , you would use the following:

 <orion-web-app>     <access-mask default="deny">         <host-access domain="saturn.apress.com" mode="allow"/>     </access-mask> </orion-web-app> 

By contrast, to block access from saturn.apress.com and all computers in subnet of 62.3.242.* , you would use the following:

 <orion-web-app>     <access-mask default="allow">         <host-access domain="saturn.apress.com" mode="deny"/>         <ip -access ip="62.3.242.199" netmask="255.255.255.0" mode="deny"/>     </access-mask> </orion-web-app> 

Summary of Overriding web.xml Settings

In addition to the many server-specific elements and attributes described earlier, a complete <web-app> element (see the standard J2EE web.xml DTD) can be placed inside the <orion-web-app> root element.

Within this <web-app> element, you can override or supplement any of the settings found in the application's web.xml file. This lets you adapt and deploy prepackaged J2EE applications with minimal configuration hassle, since you can adjust environment entries, and so on, without editing their original "clean" descriptors.



Oracle Application Server 10g. J2EE Deployment and Administration
Oracle Application Server 10g: J2EE Deployment and Administration
ISBN: 1590592352
EAN: 2147483647
Year: 2004
Pages: 150

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net