Sun Java System Application Server Enterprise Edition 8.1 2005Q2 Developer's Guide

- Previous: Part I Developing and Deploying Applications
- Next: Chapter 6 Using Enterprise JavaBeans Technology

# Chapter 5 Developing Web Applications

This chapter describes how web applications are supported in the Sun Java System Application Server and includes the following sections:

- Introducing Web Applications

- Using Servlets

- Using JavaServer Pages

- Creating and Managing HTTP Sessions

For general information about web applications, see the J2EE 1.4 Tutorial at `http://java.sun.com/j2ee/1.4/docs/tutorial/doc/WebApp.html#wp76431`.

# Introducing Web Applications

This section includes summaries of the following topics:

- Internationalization Issues

- Virtual Servers

- Default Web Modules

- Classloader Delegation

- Using the default-web.xml File

- Configuring Logging in the Web Container

- Configuring Idempotent URL Requests

- Configuring HTML Error Pages

- Header Management

- Redirecting URLs

## Internationalization Issues

This section covers internationalization as it applies to the following:

- The Server

- Servlets

### The Server

To set the default locale of the entire Application Server, which determines the locale of the Administration Console, the logs, and so on, use the Administration Console. Select the Domain component, and type a value in the Locale field. For details, see the Sun Java System Application Server Enterprise Edition 8.1 2005Q2 Administration Guide.

### Servlets

This section explains how the Application Server determines the character encoding for the servlet request and the servlet response. For encodings you can use, see `http://java.sun.com/j2se/1.4/docs/guide/intl/encoding.doc.html`.

#### Servlet Request

When processing a servlet request, the server uses the following order of precedence, first to last, to determine the request character encoding:

- The ```getCharacterEncoding()` method.

- A hidden field in the form, specified by the `form-hint-field` attribute of the `parameter-encoding` element in the `sun-web.xml` file.

- The character encoding set in the `default-charset` attribute of the `parameter-encoding` element in the `sun-web.xml` file.

- The default, which is `ISO-8859-1`.

For details about the `parameter-encoding` element, see parameter-encoding.

#### Servlet Response

When processing a servlet response, the server uses the following order of precedence, first to last, to determine the response character encoding:

- The `setCharacterEncoding()` or ```setContentType()` method.

- The ```setLocale()` method.

- The default, which is `ISO-8859-1`.

## Virtual Servers

A virtual server, also called a virtual host, is a virtual web server that serves content targeted for a specific URL. Multiple virtual servers can serve content using the same or different host names, port numbers, or IP addresses. The HTTP service directs incoming web requests to different virtual servers based on the URL.

When you first install the Application Server, a default virtual server is created. (You can also assign a default virtual server to each new HTTP listener you create. For details, see the Sun Java System Application Server Enterprise Edition 8.1 2005Q2 Administration Guide.)

Web applications and J2EE applications containing web components can be assigned to virtual servers.

### To assign virtual servers

1. Deploy the application or web module and assign the desired virtual server to it.

   For more information, see Tools for Deployment.

2. In the Administration Console, open the HTTP Service component under the relevant configuration.

3. Open the Virtual Servers component under the HTTP Service component.

4. Select the virtual server to which you want to assign a default web module.

5. Select the application or web module from the Default Web Module drop-down list.

   For more information, see Default Web Modules.

##### See Also

For details, see the Sun Java System Application Server Enterprise Edition 8.1 2005Q2 Administration Guide.

## Default Web Modules

A default web module can be assigned to the default virtual server and to each new virtual server. For details, see Virtual Servers. To access the default web module for a virtual server, point the browser to the URL for the virtual server, but do not supply a context root. For example:

    http://myvserver:3184/

A virtual server with no default web module assigned serves HTML or JSP content from its document root, which is usually domain-dir`/docroot`. To access this HTML or JSP content, point your browser to the URL for the virtual server, do not supply a context root, but specify the target file.

For example:

    http://myvserver:3184/hellothere.jsp

## Classloader Delegation

The Servlet specification recommends that the Web Classloader look in the local class loader before delegating to its parent. To make the Web Classloader follow the delegation model in the Servlet specification, set `delegate="false"` in the `class-loader` element of the `sun-web.xml` file. It’s safe to do this only for a web module that does not interact with any other modules.

The default value is `delegate="true"`, which causes the Web Classloader to delegate in the same manner as the other classloaders. Use `delegate="true"` for a web application that accesses EJB components or that acts as a web service client or endpoint. For details about `sun-web.xml`, see The sun-web.xml File.

For general information about classloaders, see Classloaders.

## Using the default-web.xml File

You can use the `default-web.xml` file to define features such as filters and security constraints that apply to all web applications.

### To use the default-web.xml file

1. Place the JAR file for the filter, security constraint, or other feature in the domain-dir`/lib` directory.

2. Edit the domain-dir`/config/default-web.xml` file to refer to the JAR file.

3. Restart the server.

##### The InvokerServlet

The `InvokerServlet` allows use of the `servlet-name` instead of the `servlet-mapping` for invoking a servlet with a URL, as described in Invoking a Servlet with a URL. The `InvokerServlet` is commented out in the `default-web.xml` file. To re-enable the `InvokerServlet`, remove the comment indicators (`<!--` and `-->`), then restart the server.

## Configuring Logging in the Web Container

For information about configuring logging and monitoring in the web container using the Administration Console, see the Sun Java System Application Server Enterprise Edition 8.1 2005Q2 Administration Guide.

## Configuring Idempotent URL Requests

An idempotent request is one that does not cause any change or inconsistency in an application when retried. To enhance the availability of your applications deployed on an Application Server cluster, configure the load balancer to retry failed idempotent HTTP requests on all the Application Server instances in a cluster. This option can be used for read-only requests, for example, to retry a search request.

This section describes the following topics:

- Specifying an Idempotent URL

- Characteristics of an Idempotent URL

### Specifying an Idempotent URL

To configure idempotent URL response, specify the URLs that can be safely retried in idempotent-url-pattern elements in the `sun-web.xml` file. For example:

    <idempotent-url-pattern url-pattern="sun_java/*" no-of-retries="10"/>

For details, see idempotent-url-pattern.

If none of the server instances can successfully serve the request, an error page is returned. To configure custom error pages, see Configuring HTML Error Pages.

### Characteristics of an Idempotent URL

Since all requests for a given session are sent to the same application server instance, and if that Application Server instance is unreachable, the load balancer returns an error message. Normally, the request is not retried on another Application Server instance. However, if the URL pattern matches that specified in the `sun-web.xml` file, the request is implicitly retried on another Application Server instance in the cluster.

In HTTP, some methods (such as GET) are idempotent, while other methods (such as POST) are not. In effect, retrying an idempotent URL should not cause values to change on the server or in the database. The only difference should be a change in the response received by the user.

Examples of idempotent requests include search engine queries and database queries. The underlying principle is that the retry does not cause an update or modification of data.

A search engine, for example, sends HTTP requests with the same URL pattern to the load balancer. Specifying the URL pattern of the search request to the load balancer ensures that HTTP requests with the specified URL pattern is implicitly retried on another Application Server instance.

For example, if the request URL sent to the Application Server is of the type `/search/`something`.html`, then the URL pattern can be specified as `/search/*`.

Examples of non-idempotent requests include banking transactions and online shopping. If you retry such requests, money might be transferred twice from your account.

## Configuring HTML Error Pages

To specify an error page (or URL to an error page) to be displayed to the end user, use the `error-url` attribute of the sun-web-app element in the `sun-web.xml` file. For example:

    <sun-web-app error-url="webserver-install-dir/error/error1.html">
    ... subelements ...
    </sun-web-app>

For details, see sun-web-app.

If the `error-url` attribute is specified, it overrides all other mechanisms configured for error reporting.

Note –

This attribute should not point to a URL on the Application Server instance, because the `error-url` cannot be loaded if the server is down. Instead, specify a URL that points to a location on the web server.

The Application Server provides the following options for specifying the error page.

- You can specify the `error-url` to be an HTTP URL. The Application Server forwards the client request to the specified error URL.

- You can specify the `error-url` to be the name of an HTML page in the standard load balancer plug-in’s error pages directory. Do not specify an absolute path in the local file system. The location must be relative to the webserver-install-dir`/plugins/lbplugin/``errorpages` directory.

- If you do not specify the `error-url` attribute in the `sun-web.xml` file, a default error page , `sun-http-lberror.html`, from the standard error pages directory, `errorpages`, is displayed if present.

  As part of the load balancer plug-in installation, a directory called `errorpages` is created in the web server installation directory.

The error page is displayed according to the following rules:

- When an error is encountered for an application, the Application Server first checks if the `error-url` attribute is defined. If it is defined, the Application Server reads the URL attribute and loads the error page.

- If the `error-url` attribute is missing or invalid, the Application Server displays the default error page, `sun-http-lb-error.html`, from the `errorpages` directory of the load balancer plug-in.

- If the `error-url` has been defined but the page is missing, the Application Server loads the default error page, `sun-http-lb-error.html`.

- If the default error page is missing, the error is forwarded to the web server.

## Header Management

In the Platform Edition of the Application Server, the `Enumeration` from `request.``getHeaders()` contains multiple elements. In the Enterprise Edition, this `Enumeration` contains a single, aggregated value.

The header names used in `HttpServletResponse.add` XXX `Header()` and `HttpServletResponse.set` XXX `Header()` are returned differently to the HTTP client from the Platform Edition and the Enterprise Edition of the Application Server. The Platform Edition preserves the names as they were created. The Enterprise Edition capitalizes the first letter but converts all other letters to lower case. For example, if `sampleHeaderName2` is used in `response.addHeader()`, the response name in the Platform Edition is unchanged, but the response name in the Enterprise Edition is `Sampleheadername2`.

## Redirecting URLs

You can specify that a request for an old URL is treated as a request for a new URL. This is called redirecting a URL.

To specify a redirected URL for a virtual server, use the `redireect_`n property, where n is a positive integer that allows specification of more than one. This property is a subelement of a `virtual-server` element in the `domain.xml` file. For more information about this element, see `virtual-server` in Sun Java System Application Server Enterprise Edition 8.1 2005Q2 Administration Reference. Each of these `redirect_`n properties is inherited by all web applications deployed on the virtual server.

The value of each `redirect_`n property has two components, which may be specified in any order:

The first component, `from`, specifies the prefix of the requested URI to match.

The second component, `url-prefix`, specifies the new URL prefix to return to the client. The `from` prefix is simply replaced by this URL prefix.

For example:

    <property name="redirect_1" value="from=/dummy url-prefix=http://etude"/>

# Using Servlets

Application Server supports the Java Servlet Specification version 2.4.

Note –

Servlet API version 2.4 is fully backward compatible with version 2.3, so all existing servlets should work without modification or recompilation.

To develop servlets, use Sun Microsystems’ Java Servlet API. For information about using the Java Servlet API, see the documentation provided by Sun Microsystems at `http://java.sun.com/products/servlet/index.html`.

The Application Server provides the `wscompile` and `wsdeploy` tools to help you implement a web service endpoint as a servlet. For more information about these tools, see the Sun Java System Application Server Enterprise Edition 8.1 2005Q2 Reference Manual.

This section describes how to create effective servlets to control application interactions running on an Application Server, including standard-based servlets. In addition, this section describes the Application Server features to use to augment the standards.

This section contains the following topics:

- Invoking a Servlet with a URL

- Servlet Output

- Caching Servlet Results

- About the Servlet Engine

## Invoking a Servlet with a URL

You can call a servlet deployed to the Application Server by using a URL in a browser or embedded as a link in an HTML or JSP file. The format of a servlet invocation URL is as follows:

    http://server:port/context-root/servlet-mapping?name=value

The following table describes each URL section.

Table 5–1 URL Fields for Servlets Within an Application

URL element | Description
--- | ---
server`:`port | The IP address (or host name) and optional port number. To access the default web module for a virtual server, specify only this URL section. You do not need to specify the context-root or servlet-name unless you also wish to specify name-value parameters.
context-root | For an application, the context root is defined in the `context-root` element of the `application.xml` or `sun-application.xml` file. For an individually deployed web module, the context root is specified during deployment. For both applications and individually deployed web modules, the default context root is the name of the WAR file minus the `.war` suffix.
servlet-mapping | The `servlet-mapping` as configured in the `web.xml` file. You can use the `servlet-name` instead if you enable the `InvokerServlet`; see Using the default-web.xml File.
`?`name`=`value`...` | Optional request parameters.

In this example, `localhost` is the host name, `MortPages` is the context root, and `calcMortgage` is the servlet mapping:

    http://localhost:8080/MortPages/calcMortgage?rate=8.0&per=360&bal=180000

When invoking a servlet from within a JSP file, you can use a relative path. For example:

    <jsp:forward page="TestServlet"/>
    <jsp:include page="TestServlet"/>

## Servlet Output

`ServletContext.log` messages are sent to the server log.

By default, the `System.out` and `System.err` output of servlets are sent to the server log, and during startup server log messages are echoed to the `System.err` output. Also by default, there is no Windows-only console for the `System.err` output.

To change these defaults using the Administration Console, select the Logger Settings component under the relevant configuration, then check or uncheck these boxes:

- Log Messages to Standard Error - If checked, `System.err` output is sent to the server log. If unchecked, `System.err` output is sent to the system default location only.

- Write to System Log - If checked, `System.out` output is sent to the server log. If unchecked, `System.out` output is sent to the system default location only.

For more information, see the Sun Java System Application Server Enterprise Edition 8.1 2005Q2 Administration Guide.

## Caching Servlet Results

The Application Server can cache the results of invoking a servlet, a JSP, or any URL pattern to make subsequent invocations of the same servlet, JSP, or URL pattern faster. The Application Server caches the request results for a specific amount of time. In this way, if another data call occurs, the Application Server can return the cached data instead of performing the operation again. For example, if your servlet returns a stock quote that updates every 5 minutes, you set the cache to expire after 300 seconds.

Whether to cache results and how to cache them depends on the data involved. For example, it makes no sense to cache the results of a quiz submission, because the input to the servlet is different each time. However, it makes sense to cache a high level report showing demographic data taken from quiz results that is updated once an hour.

To define how an Application Server web application handles response caching, you edit specific fields in the `sun-web.xml` file.

Note –

A servlet that uses caching is not portable.

A sample caching application is in install-dir`/samples/webapps/apps/caching`.

For more information about JSP caching, see JSP Caching.

The rest of this section covers the following topics:

- Caching Features

- Default Cache Configuration

- Caching Example

- CacheKeyGenerator Interface

### Caching Features

The Application Server has the following web application response caching capabilities:

- Caching is configurable based on the servlet name or the URI.

- When caching is based on the URI, this includes user specified parameters in the query string. For example, a response from `/garden/catalog?category=roses` is different from a response from `/garden/catalog?category=lilies`. These responses are stored under different keys in the cache.

- Cache size, entry timeout, and other caching behaviors are configurable.

- Entry timeout is measured from the time an entry is created or refreshed. To override this timeout for an individual cache mapping, specify the `cache-mapping` subelement `timeout`.

- To determine caching criteria programmatically, write a class that implements the `com.sun.appserv.web.cache.CacheHelper` interface. For example, if only a servlet knows when a back end data source was last modified, you can write a helper class to retrieve the last modified timestamp from the data source and decide whether to cache the response based on that timestamp.

- To determine cache key generation programmatically, write a class that implements the `com.sun.appserv.web.cache.CacheKeyGenerator` interface. See CacheKeyGenerator Interface.

- All non-ASCII request parameter values specified in cache key elements must be URL encoded. The caching subsystem attempts to match the raw parameter values in the request query string.

- Since newly updated classes impact what gets cached, the web container clears the cache during dynamic deployment or reloading of classes.

- The following `HttpServletRequest` request attributes are exposed:

  - `com.sun.appserv.web.cachedServletName`, the cached servlet target

  - `com.sun.appserv.web.cachedURLPattern`, the URL pattern being cached

- Results produced by resources that are the target of a `RequestDispatcher.include()` or `RequestDispatcher.forward()` call are cached if caching has been enabled for those resources. For details, see the descriptions of the cache-mapping and dispatcher elements in the `sun-web.xml` file.

### Default Cache Configuration

If you enable caching but do not provide any special configuration for a servlet or JSP, the default cache configuration is as follows:

- The default cache timeout is 30 seconds.

- Only the HTTP GET method is eligible for caching.

- HTTP requests with cookies or sessions automatically disable caching.

- No special consideration is given to `Pragma:`, `Cache-control:`, or `Vary:` headers.

- The default key consists of the Servlet Path (minus `pathInfo` and the query string).

- A “least recently used” list is maintained to evict cache entries if the maximum cache size is exceeded.

- Key generation concatenates the servlet path with key field values, if any are specified.

- Results produced by resources that are the target of a `RequestDispatcher.include()` or `RequestDispatcher.forward()` call are never cached.

### Caching Example

Here is an example cache element in the `sun-web.xml` file:

    <cache max-capacity="8192" timeout="60">
    <cache-helper name="myHelper" class-name="MyCacheHelper"/>
    <cache-mapping>
    	<servlet-name>myservlet</servlet-name>
    	<timeout name="timefield">120</timeout>
    	<http-method>GET</http-method>
    	<http-method>POST</http-method>
    </cache-mapping>
    <cache-mapping>
    	<url-pattern> /catalog/* </url-pattern>
    	<!-- cache the best selling category; cache the responses to
    	   -- this resource only when the given parameters exist. Cache
    	   -- only when the catalog parameter has 'lilies' or 'roses'
    	   -- but no other catalog varieties:
    	  -- /orchard/catalog?best&category='lilies'
    	  -- /orchard/catalog?best&category='roses'
    	  -- but not the result of
    	   -- /orchard/catalog?best&category='wild'
    	-->
    	<constraint-field name='best' scope='request.parameter'/>
    	<constraint-field name='category' scope='request.parameter'>
    		<value> roses </value>
    		<value> lilies </value>
    	</constraint-field>
    	 <!-- Specify that a particular field is of given range but the
    	   -- field doesn't need to be present in all the requests -->
    	<constraint-field name='SKUnum' scope='request.parameter'>
    		<value match-expr='in-range'> 1000 - 2000 </value>
    	</constraint-field>
    	<!-- cache when the category matches with any value other than
    	   -- a specific value -->
    	<constraint-field name="category" scope="request.parameter>
    		<value match-expr="equals" cache-on-match-failure="true">
           bogus
    		</value>
    	</constraint-field>
    </cache-mapping>
    <cache-mapping>
    	<servlet-name> InfoServlet </servlet-name>
    	<cache-helper-ref>myHelper</cache-helper-ref>
    </cache-mapping>
    </cache>

For more information about the `sun-web.xml` caching settings, see cache.

### CacheKeyGenerator Interface

The built-in default `CacheHelper` implementation allows web applications to customize the key generation. An application component (in a servlet or JSP) can set up a custom `CacheKeyGenerator` implementation as an attribute in the `ServletContext`.

The name of the context attribute is configurable as the `value` of the `cacheKeyGeneratorAttrName` property in the `default-helper` element of the `sun-web.xml` deployment descriptor. For more information, see default-helper.

## About the Servlet Engine

Servlets exist in and are managed by the servlet engine in the Application Server. The servlet engine is an internal object that handles all servlet meta functions. These functions include instantiation, initialization, destruction, access from other components, and configuration management. This section covers the following topics:

- Instantiating and Removing Servlets

- Request Handling

### Instantiating and Removing Servlets

After the servlet engine instantiates the servlet, the servlet engine calls the servlet’s `init()` method to perform any necessary initialization. You can override this method to perform an initialization function for the servlet’s life, such as initializing a counter.

When a servlet is removed from service, the servlet engine calls the `destroy()` method in the servlet so that the servlet can perform any final tasks and deallocate resources. You can override this method to write log messages or clean up any lingering connections that won’t be caught in garbage collection.

### Request Handling

When a request is made, the Application Server hands the incoming data to the servlet engine. The servlet engine processes the request’s input data, such as form data, cookies, session information, and URL name-value pairs, into an `HttpServletRequest` request object type.

The servlet engine also creates an `HttpServletResponse` response object type. The engine then passes both as parameters to the servlet’s `service()` method.

In an HTTP servlet, the default `service()` method routes requests to another method based on the HTTP transfer method: `POST`, `GET`, `DELETE`, `HEAD`, `OPTIONS`, `PUT`, or `TRACE`. For example, HTTP `POST` requests are sent to the `doPost()` method, HTTP `GET` requests are sent to the `doGet()` method, and so on. This enables the servlet to process request data differently, depending on which transfer method is used. Since the routing takes place in the service method, you generally do not override `service()` in an HTTP servlet. Instead, override `doGet()`, `doPost()`, and so on, depending on the request type you expect.

To perform the tasks to answer a request, override the `service()` method for generic servlets, and the `doGet()` or `doPost()` methods for HTTP servlets. Very often, this means accessing EJB components to perform business transactions, then collating the information in the request object or in a JDBC `ResultSet` object.

# Using JavaServer Pages

The Application Server supports the following JSP features:

- JavaServer Pages (JSP) Specification version 2.0

- Precompilation of JSP files, which is especially useful for production servers

- JSP tag libraries and standard portable tags

For information about creating JSP files, see Sun Microsystem’s JavaServer Pages web site at `http://java.sun.com/products/jsp/index.html`.

For information about Java Beans, see Sun Microsystem’s JavaBeans web page at `http://java.sun.com/beans/index.html`.

This section describes how to use JavaServer Pages (JSP files) as page templates in an Application Server web application. This section contains the following topics:

- JSP Tag Libraries and Standard Portable Tags

- JSP Caching

- Options for Compiling JSP Files

## JSP Tag Libraries and Standard Portable Tags

Application Server supports tag libraries and standard portable tags. For more information, see the JavaServer Pages Standard Tag Library (JSTL) page at `http://java.sun.com/products/jsp/jstl/index.jsp`.

Web applications don’t need to bundle copies of the `jsf-impl.jar` or `appserv-jstl.jar` JSP tag libraries (in install-dir`/lib`) to use JavaServerTM Faces technology or JSTL, respectively. These tag libraries are automatically available to all web applications.

However, the install-dir`/lib/``appserv-tags.jar` tag library for JSP caching is not automatically available to web applications. See JSP Caching, next.

## JSP Caching

JSP caching lets you cache tag invocation results within the Java engine. Each can be cached using different cache criteria. For example, suppose you have invocations to view stock quotes, weather information, and so on. The stock quote result can be cached for 10 minutes, the weather report result for 30 minutes, and so on.

For more information about response caching as it pertains to servlets, see Caching Servlet Results.

JSP caching is implemented by a tag library packaged into the install-dir`/lib/``appserv-tags.jar` file, which you can copy into the `WEB-INF/lib` directory of your web application. The `appserv-tags.tld` tag library descriptor file is in the `META-INF` directory of this JAR file.

Note –

Web applications that use this tag library are not portable.

To allow all web applications to share this tag library, change the following elements in the `domain.xml` file. Change this:

    <jvm-options>
    -Dcom.sun.enterprise.taglibs=appserv-jstl.jar,jsf-impl.jar
    </jvm-options>

to this:

    <jvm-options>
    -Dcom.sun.enterprise.taglibs=appserv-jstl.jar,jsf-impl.jar,appserv-tags.jar
    </jvm-options>

and this:

    <jvm-options>
    -Dcom.sun.enterprise.taglisteners=jsf-impl.jar
    </jvm-options>

to this:

    <jvm-options>
    -Dcom.sun.enterprise.taglisteners=jsf-impl.jar,appserv-tags.jar
    </jvm-options>

For more information about the `domain.xml` file, see the Sun Java System Application Server Enterprise Edition 8.1 2005Q2 Administration Reference.

Refer to these tags in JSP files as follows:

    <%@ taglib prefix="prefix" uri="Sun ONE Application Server Tags" %>

Subsequently, the cache tags are available as `<`prefix`:cache>` and `<`prefix`:flush>`. For example, if your prefix is `mypfx`, the cache tags are available as `<mypfx:cache>` and `<mypfx:flush>`.

The tags are as follows:

- cache

- flush

### cache

The cache tag caches the body between the beginning and ending tags according to the attributes specified. The first time the tag is encountered, the body content is executed and cached. Each subsequent time it is run, the cached content is checked to see if it needs to be refreshed and if so, it is executed again, and the cached data is refreshed. Otherwise, the cached data is served.

#### Attributes

The following table describes attributes for the `cache` tag.

Table 5–2 `cache` Attributes

Attribute | Default | Description
--- | --- | ---
`key` | ServletPath`_`Suffix | (optional) The name used by the container to access the cached entry. The cache key is suffixed to the servlet path to generate a key to access the cached entry. If no key is specified, a number is generated according to the position of the tag in the page.
`timeout` | `60s` | (optional) The time in seconds after which the body of the tag is executed and the cache is refreshed. By default, this value is interpreted in seconds. To specify a different unit of time, add a suffix to the timeout value as follows: `s` for seconds, `m` for minutes, `h` for hours, `d` for days. For example, `2h` specifies two hours.
`nocache` | `false` | (optional) If set to `true`, the body content is executed and served as if there were no `cache` tag. This offers a way to programmatically decide whether the cached response is sent or whether the body has to be executed, though the response is not cached.
`refresh` | `false` | (optional) If set to `true`, the body content is executed and the response is cached again. This lets you programmatically refresh the cache immediately regardless of the `timeout` setting.

#### Example

The following example represents a cached JSP file:

    <%@ taglib prefix="mypfx" uri="Sun ONE Application Server Tags" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <mypfx:cache                 key="${sessionScope.loginId}"
    			nocache="${param.nocache}"
    			refresh="${param.refresh}"
    			timeout="10m">
    <c:choose>
    	<c:when test="${param.page == 'frontPage'}">
    		<%-- get headlines from database --%>
    	</c:when>
    	<c:otherwise>
    		...
    	</c:otherwise>
    </c:choose>
    </mypfx:cache>
    <mypfx:cache timeout="1h">
    <h2> Local News </h2>
    	<%-- get the headline news and cache them --%>
    </mypfx:cache>

### flush

Forces the cache to be flushed. If a `key` is specified, only the entry with that key is flushed. If no key is specified, the entire cache is flushed.

#### Attributes

The following table describes attributes for the `flush` tag.

Table 5–3 `flush` Attributes

Attribute | Default | Description
--- | --- | ---
`key` | ServletPath`_`Suffix | (optional) The name used by the container to access the cached entry. The cache key is suffixed to the servlet path to generate a key to access the cached entry. If no key is specified, a number is generated according to the position of the tag in the page.

#### Examples

To flush the entry with `key="foobar"`:

    <mypfx:flush key="foobar"/>

To flush the entire cache:

    <c:if test="${empty sessionScope.clearCache}">
       <mypfx:flush />
    </c:if>

#### Options for Compiling JSP Files

Application Server provides the following ways of compiling JSP 2.0 compliant source files into servlets:

- JSP files are automatically compiled at runtime.

- The `asadmin deploy` command has a `precompilejsp` option. For details, see the Sun Java System Application Server Enterprise Edition 8.1 2005Q2 Reference Manual.

- The `sun-appserv-jspc` Ant task allows you to precompile JSP files; see sun-appserv-jspc.

- The `jspc` command line tool allows you to precompile JSP files at the command line. For details, see the Sun Java System Application Server Enterprise Edition 8.1 2005Q2 Reference Manual.

# Creating and Managing HTTP Sessions

This chapter describes how to create and manage a session that allows users and transaction information to persist between interactions.

This chapter contains the following sections:

- Configuring Sessions

- Session Managers

- Sample Session Persistence Applications

## Configuring Sessions

This section covers the following topics:

- Sessions, Cookies, and URL Rewriting

- Coordinating Session Access

- Distributed Sessions and Persistence

### Sessions, Cookies, and URL Rewriting

To configure whether and how sessions use cookies and URL rewriting, edit the `session-properties` and `cookie-properties` elements in the `sun-web.xml` file for an individual web application. See session-properties and cookie-properties for more about the properties you can configure.

For information about configuring default session properties for the entire web container, see the Sun Java System Application Server Enterprise Edition 8.1 2005Q2 Administration Guide and the Sun Java System Application Server Enterprise Edition 8.1 2005Q2 High Availability Administration Guide.

### Coordinating Session Access

Make sure that multiple threads don’t simultaneously modify the same session object in conflicting ways. If the persistence type is `ha` (see The ha Persistence Type), the following message in the log file indicates that this might be happening:

    Primary Key Constraint violation while saving session session_id

This is especially likely to occur in web applications that use HTML frames where multiple servlets are executing simultaneously on behalf of the same client. A good solution is to ensure that one of the servlets modifies the session and the others have read-only access.

### Distributed Sessions and Persistence

A distributed session can run in multiple Application Server instances, provided the following criteria are met:

- Each server instance has access to the same high-availability database (HADB). For information about how to enable this database, see the description of the `configure-ha-cluster` command in the Sun Java System Application Server Enterprise Edition 8.1 2005Q2 Reference Manual.

- Each server instance has the same distributable web application deployed to it. The `web-app` element of the `web.xml` deployment descriptor file must have the `distributable` subelement specified.

- The web application uses high-availability session persistence. If a non-distributable web application is configured to use high-availability session persistence, an error is written to the server log. See The ha Persistence Type.

- All objects bound into a distributed session must be of the types listed in Table 5–4.

- The web application must be deployed using the `deploy` or `deploydir` command with the `--availabilityenabled` option set to `true`. See the Sun Java System Application Server Enterprise Edition 8.1 2005Q2 Reference Manual.

Note –

Contrary to the Servlet 2.4 specification, Application Server does not throw an `IllegalArgumentException` if an object type not supported for failover is bound into a distributed session.

Keep the distributed session size as small as possible. Session size has a direct impact on overall system throughput.

A servlet that is not deployed as part of a web application is implicitly deployed to a default web application and has the default `ServletContext`. The default `ServletContext` is not distributed. (A web application with an empty context root does not have the default `ServletContext`.)

In the event of an instance or hardware failure, another server instance can take over a distributed session, with the following limitations:

- If a distributable web application references a J2EE component or resource, the reference might be lost. See Table 5–4 for a list of the types of references that HTTPSession failover supports.

- References to open files or network connections are lost.

For information about how to work around these limitations, see the Sun Java System Application Server Enterprise Edition 8.1 2005Q2 Deployment Planning Guide.

In the following table, No indicates that failover for the object type might not work in all cases and that no failover support is provided. However, failover might work in some cases for that object type. For example, failover might work because the class implementing that type is serializable.

For more information about the `InitialContext`, see Accessing the Naming Context. For more information about transaction recovery, see Chapter 12, Using the Transaction Service. For more information about Administered Objects, see Creating Physical Destinations.

Table 5–4 Object Types Supported for J2EE Web Application Session State Failover

Java Object Type | Failover Support
--- | ---
Stateless session, stateful session, and entity bean local home reference, local object reference | Yes
Colocated and distributed stateless session, stateful session, and entity bean remote home reference, remote reference | Yes
JNDI Context | Yes, `InitialContext` and `java:comp/env`
UserTransaction | Yes, but if the instance that fails is never restarted, any prepared global transactions are lost and might not be correctly rolled back or committed
JDBC DataSource | No
JavaTM Message Service (JMS) ConnectionFactory, Destination | No
JavaMailTM Session | No
Connection Factory | No
Administered Object | No
Web service reference | No
Serializable Java types | Yes

## Session Managers

A session manager automatically creates new session objects whenever a new session starts. In some circumstances, clients do not join the session, for example, if the session manager uses cookies and the client does not accept cookies.

Application Server offers these session management options, determined by the session-manager element’s `persistence-type` attribute in the `sun-web.xml` file:

- The memory Persistence Type, the default

- The file Persistence Type, which uses a file to store session data

- The ha Persistence Type, which uses the high-availability database for session persistence

Note –

If the session manager configuration contains an error, the error is written to the server log and the default (`memory`) configuration is used.

### The memory Persistence Type

This persistence type is not designed for a production environment that requires session persistence. It provides no session persistence. However, you can configure it so that the session state in memory is written to the file system prior to server shutdown.

To specify the `memory` persistence type for the entire web container, use the `configure-ha-persistence` command. For details, see the Sun Java System Application Server Enterprise Edition 8.1 2005Q2 Reference Manual.

To specify the `memory` persistence type for a specific web application, edit the `sun-web.xml` file as in the following example. The `persistence-type` property is optional, but must be set to `memory` if included. This overrides the web container availability settings for the web application.

    <sun-web-app>
    ...
    <session-config>
    	<session-manager persistence-type=memory />
    		<manager-properties>
    			<property name="sessionFilename" value="sessionstate" />
    		</manager-properties>
    	</session-manager>
    	...
    </session-config>
    ...
    </sun-web-app>

The only manager property that the `memory` persistence type supports is sessionFilename, which is listed under manager-properties.

For more information about the `sun-web.xml` file, see The sun-web.xml File.

### The file Persistence Type

This persistence type provides session persistence to the local file system, and allows a single server domain to recover the session state after a failure and restart. The session state is persisted in the background, and the rate at which this occurs is configurable. The store also provides passivation and activation of the session state to help control the amount of memory used. This option is not supported in a production environment. However, it is useful for a development system with a single server instance.

Note –

Make sure the `delete` option is set in the `server.policy` file, or expired file-based sessions might not be deleted properly. For more information about `server.policy`, see The server.policy File.

To specify the `file` persistence type for the entire web container, use the `configure-ha-persistence` command. For details, see the Sun Java System Application Server Enterprise Edition 8.1 2005Q2 Reference Manual.

To specify the `file` persistence type for a specific web application, edit the `sun-web.xml` file as in the following example. Note that `persistence-type` must be set to `file`. This overrides the web container availability settings for the web application.

    <sun-web-app>
    ...
    <session-config>
    	<session-manager persistence-type=file>
    		<store-properties>
    			<property name=directory value=sessiondir />
    		</store-properties>
    	</session-manager>
    	...
    </session-config>
    ...
    </sun-web-app>

The `file` persistence type supports all the manager properties listed under manager-properties except `sessionFilename`, and supports the `directory` store property listed under store-properties.

For more information about the `sun-web.xml` file, see The sun-web.xml File.

### The ha Persistence Type

The ha persistence type uses the high-availability database (HADB) for session persistence. The HADB allows sessions to be distributed. For details, see Distributed Sessions and Persistence. In addition, you can configure the frequency and scope of session persistence. The HADB is also used as the passivation and activation store. Use this option in a production environment that requires session persistence.

The HADB must be configured and enabled before you can use distributed sessions. For configuration details, see the description of the `configure-ha-cluster` command in the Sun Java System Application Server Enterprise Edition 8.1 2005Q2 Reference Manual.

To enable the HADB, select the Availability Service component under the relevant configuration in the Administration Console. Check the Instance Level Availability box. To enable availability for the web container, select the Web Container Availability tab, then check the Availability Service box. For details, see the Sun Java System Application Server Enterprise Edition 8.1 2005Q2 High Availability Administration Guide.

To change settings such as persistence frequency and persistence scope for the entire web container, see the description of the `configure-ha-persistence` command in the Sun Java System Application Server Enterprise Edition 8.1 2005Q2 Reference Manual.

To specify the `ha` persistence type for a specific web application, edit the `sun-web.xml` file as in the following example. Note that `persistence-type` must be set to `ha`. This overrides the web container availability settings for the web application.

    <sun-web-app>
    ...
    <session-config>
    	<session-manager persistence-type=fileha>
    		<manager-properties>
    			<property name=persistenceFrequency value=web-method />
    		</manager-properties>
    		<store-properties>
    			<property name=persistenceScope value=session />
    		</store-properties>
    	</session-manager>
    	...
    </session-config>
    ...
    </sun-web-app>

The `ha` persistence type supports all the manager properties listed under manager-properties except `sessionFilename`, and supports the `persistenceScope` store property listed under store-properties.

For more information about the `sun-web.xml` file, see The sun-web.xml File.

## Sample Session Persistence Applications

The following directories contain sample applications that demonstrate HTTP session persistence:

    install-dir/samples/ee-samples/highavailability

    install-dir/samples/ee-samples/failover

- Previous: Part I Developing and Deploying Applications
- Next: Chapter 6 Using Enterprise JavaBeans Technology

- © 2010, Oracle Corporation and/or its affiliates