Sun GlassFish Enterprise Server v2.1.1 Developer's Guide

Chapter 8 Developing Web and SIP Applications

This chapter describes how web applications are supported in the Sun GlassFish Enterprise Server and includes the following sections:

For general information about web applications, see “Part One: The Web Tier” in the Java EE 5 Tutorial.

Using Servlets

Enterprise Server supports the Java Servlet Specification version 2.5.


Note –

Servlet API version 2.5 is fully backward compatible with versions 2.3 and 2.4, 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 Enterprise 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 GlassFish Enterprise Server v2.1.1 Reference Manual.

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

This section contains the following topics:

Invoking a Servlet With a URL

You can call a servlet deployed to the Enterprise 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 8–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, sun-application.xml, or sun-web.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.

?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.

You can change these defaults using the Admin Console. In the developer profile, select the Enterprise Server component and the Logging tab. In the cluster profile, select the Logger Settings component under the relevant configuration. Then check or uncheck Write to System Log. If this box is checked, System.out output is sent to the server log. If it is unchecked, System.out output is sent to the system default location only.

For more information, click the Help button in the Admin Console from the Logging page.

Caching Servlet Results

The Enterprise 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 Enterprise Server caches the request results for a specific amount of time. In this way, if another data call occurs, the Enterprise 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 Enterprise 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.


For Javadoc tool pages relevant to caching servlet results, go to http://glassfish.dev.java.net/nonav/javaee5/api/index.html and click on the com.sun.appserv.web.cache package.

For information about JSP caching, see JSP Caching.

The rest of this section covers the following topics:

Caching Features

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

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:

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 in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

The 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 in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

About the Servlet Engine

Servlets exist in and are managed by the servlet engine in the Enterprise 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

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 Enterprise 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 Enterprise Server supports the following JSP features:

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 Enterprise Server web application. This section contains the following topics:

JSP Tag Libraries and Standard Portable Tags

Enterprise 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 as-install/lib) to use JavaServerTM Faces technology or JSTL, respectively. These tag libraries are automatically available to all web applications.

However, the as-install/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. JSP caching is described in the following topics:

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

The appserv-tags.jar File

JSP caching is implemented by a tag library packaged into the as-install/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 without bundling it 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 GlassFish Enterprise Server v2.1.1 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>.

Caching Scope

JSP caching is available in three different scopes: request, session, and application. The default is application. To use a cache in request scope, a web application must specify the com.sun.appserv.web.taglibs.cache.CacheRequestListener in its web.xml deployment descriptor, as follows:

<listener>
   <listener-class>
      com.sun.appserv.web.taglibs.cache.CacheRequestListener
   </listener-class>
</listener>

Likewise, for a web application to utilize a cache in session scope, it must specify the com.sun.appserv.web.taglibs.cache.CacheSessionListener in its web.xml deployment descriptor, as follows:

<listener>
   <listener-class>
      com.sun.appserv.web.taglibs.cache.CacheSessionListener
   </listener-class>
</listener>

To utilize a cache in application scope, a web application need not specify any listener. The com.sun.appserv.web.taglibs.cache.CacheContextListener is already specified in the appserv-tags.tld file.

The cache Tag

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 of cache

The following table describes attributes for the cache tag.

Table 8–2 The 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.

scope

application

(optional) The scope of the cache. Can be request, session, or application. See Caching Scope.

Example of cache

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>

The flush Tag

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 of flush

The following table describes attributes for the flush tag.

Table 8–3 The 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. 

scope

application

(optional) The scope of the cache. Can be request, session, or application. See Caching Scope.

Examples of flush

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

Enterprise Server provides the following ways of compiling JSP 2.1 compliant source files into servlets:

Creating and Managing Sessions

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

This chapter contains the following sections:

Configuring Sessions

This section covers the following topics:

HTTP Sessions, Cookies, and URL Rewriting

To configure whether and how HTTP 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. For more about the properties you can configure, see session-properties in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide and cookie-properties in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

For information about configuring default session properties for the entire web container, see Chapter 8, SIP, Web, and EJB Containers, in Sun GlassFish Enterprise Server v2.1.1 Administration Guide and the Sun GlassFish Enterprise Server v2.1.1 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 SIP applications where multiple SIP sessions share a SIP application session, and in converged applications where requests for the same session occur through HTTP and SIP protocols. It is likely to occur in pure 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


Note –

Some topics in the documentation pertain to features that are available only in domains that are configured to support clusters. Examples of domains that support clusters are domains that are created with the cluster profile or the enterprise profile. For information about profiles, see Usage Profiles in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.


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


Note –

Contrary to the Servlet 2.5 specification, Enterprise 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.


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

For information about how to work around these limitations, see the Sun GlassFish Enterprise Server v2.1.1 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 16, Using the Transaction Service. For more information about Administered Objects, see Creating Physical Destinations.

Table 8–4 Object Types Supported for Java EE Web Application Session State Failover

Java Object Type 

Failover Support 

Colocated or distributed stateless session, stateful session, or entity bean 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 

Java Message Service (JMS) ConnectionFactory, Destination 

No 

JavaMail Session 

No 

Connection Factory 

No 

Administered Object 

No 

Web service reference 

No 

Serializable Java types 

Yes 

Extended persistence context 

No 

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.

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


Note –

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


For more information, see session-manager in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

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 GlassFish Enterprise Server v2.1.1 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 in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

For more information about the sun-web.xml file, see Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

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 GlassFish Enterprise Server v2.1.1 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 in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide except sessionFilename, and supports the directory store property listed under store-properties in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

For more information about the sun-web.xml file, see Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

The replicated Persistence Type

The replicated persistence type uses other servers in the cluster for session persistence. Clustered server instances replicate session state in a predictive manner so that the state is saved where it is most likely to be needed. Each backup instance stores the replicated data in memory. This 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 other servers are also used as the passivation and activation store. Use this option in a production environment that requires session persistence.


Note –

Some topics in the documentation pertain to features that are available only in domains that are configured to support clusters. Examples of domains that support clusters are domains that are created with the cluster profile or the enterprise profile. For information about profiles, see Usage Profiles in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.


To use the replicated persistence type, you must first enable availability. Select the Availability Service component under the relevant configuration in the Admin Console. Check the Availability Service box. To enable availability for the web container, select the Web Container Availability tab, then check the Availability Service box. All instances in a Enterprise Server cluster should have the same availability settings to ensure consistent behavior. For details, see the Sun GlassFish Enterprise Server v2.1.1 High Availability Administration Guide.

To change settings such as persistence frequency and persistence scope for the entire web container, use the Persistence Frequency and Persistence Scope drop-down lists on the Web Container Availability tab in the Admin Console, or use the asadmin set command. For example:


asadmin set 
server-config.availability-service.web-container-availability.persistence-frequency=time-based

For more information, see the description of the asadmin set command in the Sun GlassFish Enterprise Server v2.1.1 Reference Manual.

To specify the replicated 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 replicated. This overrides the web container availability settings for the web application.

<sun-web-app>
...
<session-config>
	<session-manager persistence-type="replicated">
		<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 replicated persistence type supports all the manager properties listed under manager-properties in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide except sessionFilename, and supports the persistenceScope store property listed under store-properties in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

For more information about the sun-web.xml file, see Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

The ha Persistence Type

The ha persistence type uses the high-availability database (HADB) for session persistence. The HADB must be installed and the enterprise profile must be selected. For information about profiles, see Usage Profiles in Sun GlassFish Enterprise Server v2.1.1 Administration Guide.

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 GlassFish Enterprise Server v2.1.1 Reference Manual.

To enable the HADB, select the Availability Service component under the relevant configuration in the Admin 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. All instances in an Enterprise Server cluster should have the same availability settings to ensure consistent behavior. For details, see the Sun GlassFish Enterprise Server v2.1.1 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 GlassFish Enterprise Server v2.1.1 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="ha">
		<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 in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide except sessionFilename, and supports the persistenceScope store property listed under store-properties in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

For more information about the sun-web.xml file, see Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

Advanced Web Application Features

This section includes summaries of the following topics:

Internationalization Issues

This section covers internationalization as it applies to the following:

The Server's Default Locale

To set the default locale of the entire Enterprise Server, which determines the locale of the Admin Console, the logs, and so on, use the Admin Console. In the developer profile, select the Enterprise Server component, the Advanced tab, and the Domain Attributes tab. In the cluster profile, select the domain component. Then type a value in the Locale field. For details, click the Help button in the Admin Console.

Servlet Character Encoding

This section explains how the Enterprise Server determines the character encoding for the servlet request and the servlet response. For encodings you can use, see http://java.sun.com/javase/6/docs/technotes/guides/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:

For details about the parameter-encoding element, see parameter-encoding in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

Servlet Response

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

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 Enterprise Server, a default virtual server is created. You can also assign a default virtual server to each new HTTP listener you create.

Web applications and Java EE applications containing web components (web modules) can be assigned to virtual servers during deployment. A web module can be assigned to more than one virtual server, and a virtual server can have more than one web module assigned to it.

For more information about virtual servers, see virtual-server in Sun GlassFish Enterprise Server v2.1.1 Administration Reference.

ProcedureTo Assign a Default Virtual Server

  1. In the Admin Console, open the HTTP Service component under the relevant configuration.

  2. Open the HTTP Listeners component under the HTTP Service component.

  3. Select or create a new HTTP listener.

  4. Select from the Default Virtual Server drop-down list.

    For more information, see Default Web Modules.

See Also

For details, click the Help button in the Admin Console from the HTTP Listeners page.

ProcedureTo Assign Virtual Servers

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

    For more information, see Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

  2. In the Admin 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, click the Help button in the Admin Console from the Virtual Servers page.

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 JavaServer PagesTM (JSPTM) 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

Class Loader Delegation

The Servlet specification recommends that the Web class loader look in the local class loader before delegating to its parent. To make the Web class loader 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 class loader to delegate in the same manner as the other class loaders. 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 Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

For general information about class loaders, see Chapter 2, Class Loaders.

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.

For example, you can disable directory listings for added security. In your domain's default-web.xml file, search for the definition of the servlet whose servlet-name is equal to default, and set the value of the init-param named listings to false. Then redeploy your web application if it has already been deployed.

<init-param>
   <param-name>listings</param-name>
   <param-value>false</param-value>
</init-param>

The mime-mapping elements in default-web.xml are global and inherited by all web applications. You can override these mappings or define your own using mime-mapping elements in your web application's web.xml file. For more information about mime-mapping elements, see the Servlet specification.

You can use the Admin Console to edit the default-web.xml file. For details, click the Help button in the Admin Console. As an alternative, you can edit the file directly using the following steps.

ProcedureTo 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.

Configuring Logging and Monitoring in the Web Container

For information about configuring logging and monitoring in the web container using the Admin Console, click the Help button in the Admin Console. In the developer profile, Logging and Monitor tabs are accessible from the Application Server page. In the Cluster profile, select Logger Settings under the relevant configuration, or select the Stand-Alone Instances component, select the instance from the table, and select the Monitor tab.

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 Enterprise Server cluster, configure the load balancer to retry failed idempotent HTTP requests on all the Enterprise 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

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 in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide.

If none of the server instances can successfully serve the request, an error page is returned.

Characteristics of an Idempotent URL

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

For example, if the request URL sent to the Enterprise 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.

Header Management

In all Editions of the Enterprise Server, the Enumeration from request.getHeaders() contains multiple elements (one element per request header) instead of a single, aggregated value.

The header names used in HttpServletResponse.addXXXHeader() and HttpServletResponse.setXXXHeader() are returned as they were created.

Configuring Valves and Catalina Listeners

You can configure custom valves and Catalina listeners for web modules or virtual servers by defining properties. In the domain.xml file, valve and listener properties look like this:

<web-module ...>
   <property name="valve_1" value="org.glassfish.extension.Valve"/>
   <property name="listener_1" value="org.glassfish.extension.MyLifecycleListener"/>
</web-module>

You can define these properties in one of the following ways, then restart the server:

Alternate Document Roots

An alternate document root (docroot) allows a web application to serve requests for certain resources from outside its own docroot, based on whether those requests match one (or more) of the URI patterns of the web application's alternate docroots.

To specify an alternate docroot for a web application or a virtual server, use the alternatedocroot_n property, where n is a positive integer that allows specification of more than one. This property can be a subelement of a sun-web-app element in the sun-web.xml file or a virtual-server element in the domain.xml file. For more information about these elements, see sun-web-app in Sun GlassFish Enterprise Server v2.1.1 Application Deployment Guide and virtual-server in Sun GlassFish Enterprise Server v2.1.1 Administration Reference.

A virtual server's alternate docroots are considered only if a request does not map to any of the web modules deployed on that virtual server. A web module's alternate docroots are considered only once a request has been mapped to that web module.

If a request matches an alternate docroot's URI pattern, it is mapped to the alternate docroot by appending the request URI (minus the web application's context root) to the alternate docroot's physical location (directory). If a request matches multiple URI patterns, the alternate docroot is determined according to the following precedence order:

For example, the following properties specify three docroots. The URI pattern of the first alternate docroot uses an exact match, whereas the URI patterns of the second and third alternate docroots use extension and longest path prefix matches, respectively.

<property name="alternatedocroot_1" value="from=/my.jpg dir=/srv/images/jpg"/>
<property name="alternatedocroot_2" value="from=*.jpg dir=/srv/images/jpg"/>
<property name="alternatedocroot_3" value="from=/jpg/* dir=/src/images"/>

The value of each alternate docroot has two components: The first component, from, specifies the alternate docroot's URI pattern, and the second component, dir, specifies the alternate docroot's physical location (directory).

Suppose the above examples belong to a web application deployed at http://company22.com/myapp. The first alternate docroot maps any requests with this URL:


http://company22.com/myapp/my.jpg

To this resource:


/svr/images/jpg/my.jpg

The second alternate docroot maps any requests with a *.jpg suffix, such as:


http://company22.com/myapp/*.jpg

To this physical location:


/svr/images/jpg

The third alternate docroot maps any requests whose URI starts with /myapp/jpg/, such as:


http://company22.com/myapp/jpg/*

To the same directory as the second alternate docroot.

For example, the second alternate docroot maps this request:


http://company22.com/myapp/abc/def/my.jpg

To:


/srv/images/jpg/abc/def/my.jpg

The third alternate docroot maps:


http://company22.com/myapp/jpg/abc/resource

To:


/srv/images/jpg/abc/resource

If a request does not match any of the target web application's alternate docroots, or if the target web application does not specify any alternate docroots, the request is served from the web application's standard docroot, as usual.

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 redirect_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 GlassFish Enterprise Server v2.1.1 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"/>

Enabling Comet Support

To enable Comet support for an HTTP listener and all its associated web applications, set the cometSupport property to true. For more information, see http-listener in Sun GlassFish Enterprise Server v2.1.1 Administration Reference.

If your servlet or JSP page uses Comet technology, make sure it is initialized when the Enterprise Server starts up by adding the load-on-startup element to your web.xml file. For example:

<servlet>
   <servlet-name>CheckIn</servlet-name>
   <servlet-class>CheckInServlet</servlet-class>
   <load-on-startup>0</load-on-startup>
</servlet>

Using a context.xml File

Use the contextXmlDefault property to specify the location, relative to domain-dir, of the context.xml file for a virtual server. For more information about virtual servers, see Virtual Servers. For more information about the context.xml file, see The Context Container.

Enabling WebDav

To enable WebDav in the Enterprise Server, you edit the web.xml and sun-web.xml files as follows.

First, enable the WebDav servlet in your web.xml file:

<servlet>
   <servlet-name>webdav</servlet-name>
   <servlet-class>org.apache.catalina.servlets.WebdavServlet</servlet-class>
   <init-param>
      <param-name>debug</param-name>
      <param-value>0</param-value>
   </init-param>
   <init-param>
      <param-name>listings</param-name>
      <param-value>true</param-value>
   </init-param>
   <init-param>
      <param-name>readonly</param-name>
      <param-value>false</param-value>
   </init-param>
</servlet>

Then define the servlet mapping associated with your WebDav servlet in your web.xml file:

<servlet-mapping>
   <servlet-name>webdav</servlet-name>
   <url-pattern>/webdav/*</url-pattern>
</servlet-mapping>

To protect the WebDav servlet so other users can't modify it, add a security constraint in your web.xml file:

<security-constraint>
   <web-resource-collection>
      <web-resource-name>Login Resources</web-resource-name>
      <url-pattern>/webdav/*</url-pattern>
   </web-resource-collection>
   <auth-constraint>
      <role-name>Admin</role-name>
   </auth-constraint>
   <user-data-constraint>
      <transport-guarantee>NONE</transport-guarantee>
   </user-data-constraint>
   <login-config>
      <auth-method>BASIC</auth-method>
      <realm-name>default</realm-name>
   </login-config>
   <security-role>
      <role-name>Admin</role-name>
   </security-role>
</security-constraint>

Then define a security role mapping in your sun-web.xml file:

<security-role-mapping>
   <role-name>Admin</role-name>
   <group-name>Admin</group-name>
</security-role-mapping>

If you are using the file realm, create a user and password. For example:


asadmin create-file-user --user admin --host localhost --port 4848 --terse=true 
--groups Admin --authrealmname default admin

You can now use any WebDav client by connecting to the WebDav servlet URL, which has this format:


http://host:port/context-root/webdav/file

For example:


http://localhost:80/glassfish-webdav/webdav/index.html

You can add the WebDav servlet to your default-web.xml file to enable it for all applications, but you can't set up a security role mapping to protect it.

Using mod_jk

To set up mod_jk, follow these steps:

  1. Obtain the following software:

  2. Install mod_jk as described at http://tomcat.apache.org/connectors-doc/webserver_howto/apache.html.

  3. Copy the following Tomcat and Jakarta Commons files to as-install/lib:

    • tomcat-ajp.jar

    • commons-logging.jar

    • commons-modeler.jar

  4. Create and configure the following files:

    Examples of these files are shown after these steps. If you use both worker.properties and glassfish-jk.properties files, the file referenced by httpd.conf, or referenced by httpd.conf first, takes precedence.

  5. Start httpd.

  6. Enable mod_jk using the following command:


    asadmin create-jvm-options -Dcom.sun.enterprise.web.connector.enableJK=8009
  7. If you are using the glassfish-jk.properties file and not referencing it in httpd.conf, point to it using the following command:


    asadmin create-jvm-options 
    -Dcom.sun.enterprise.web.connector.enableJK.propertyFile=domain-dir/config/glassfish-jk.properties
  8. Restart the Enterprise Server.

Here is an example httpd.conf file:

LoadModule jk_module /usr/lib/httpd/modules/mod_jk.so
JkWorkersFile /etc/httpd/conf/worker.properties
# Where to put jk logs
JkLogFile /var/log/httpd/mod_jk.log
# Set the jk log level [debug/error/info]
JkLogLevel debug
# Select the log format
JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "
# JkOptions indicate to send SSL KEY SIZE,
JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories
# JkRequestLogFormat set the request format
JkRequestLogFormat "%w %V %T"
# Send all jsp requests to GlassFish
JkMount /*.jsp worker1
# Send all glassfish-test requests to GlassFish
JkMount /glassfish-test/* worker1

Here is an example worker.properties or glassfish-jk.properties file:

# Define 1 real worker using ajp13
worker.list=worker1
# Set properties for worker1 (ajp13)
worker.worker1.type=ajp13
worker.worker1.host=localhost.localdomain
worker.worker1.port=8009
worker.worker1.lbfactor=50
worker.worker1.cachesize=10
worker.worker1.cache_timeout=600
worker.worker1.socket_keepalive=1
worker.worker1.socket_timeout=300