Sun Java System Application Server Platform Edition 8 Developer's Guide |
Chapter 6
Developing Web ApplicationsThis chapter describes how web applications are supported in Sun Java System Application Server 8 and includes the following sections:
For general information about web applications, see the J2EE tutorial:
http://java.sun.com/j2ee/1.4/docs/tutorial/doc/WebApp.html#wp76431
Introducing Web ApplicationsThis section includes summaries of the following topics:
Internationalization Issues
This section covers internationalization as it applies to the following:
The Server
To set the default locale of the entire Sun Java System Application Server, which determines the locale of the Administration Console, the logs, and so on, do one of the following:
Servlets
This section explains how the Sun Java System 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 setCharacterEncoding() 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 more information about the parameter-encoding element, see “parameter-encoding” on page 183.
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 may serve content using the same or different host names, port numbers, or IP addresses. The HTTP service can direct incoming web requests to different virtual servers based on the URL.
When you first install Sun Java System 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 Administration Guide.)
Web applications and J2EE applications containing web components can be assigned to virtual servers. You can assign virtual servers in either of these ways:
Using the Administration Console
To use the Administration Console to assign virtual servers:
- Deploy the application or web module and assign the desired virtual server to it as described in “Tools for Deployment” on page 106.
- Login to the Administration Console by going to the following URL in your web browser:
http://host:port/asadmin
For example:
http://localhost:4848/asadmin
- Open the HTTP Service component.
- Open the Virtual Servers component under the HTTP Service component.
- Select the virtual server to which you want to assign a default web module.
- Select the application or web module from the Default Web Module drop-down list.
- Select the Save button.
For more information, see Default Web Modules.
Editing the domain.xml File
When a web module is deployed as part of an application, a j2ee-application element is created for it in domain.xml during deployment. When a web module is deployed as an individual module, a web-module element is created for it in domain.xml during deployment. The j2ee-application and web-module elements both have a virtual-servers attribute, which specifies a list of virtual server IDs. The virtual-servers attribute is empty by default, which means that the web application is assigned to all virtual servers.
Each virtual-server element in domain.xml has a default-web-module attribute, which allows you to configure a default web module for each virtual server. A default web module for the default virtual server is provided at installation. For more information, see Default Web Modules.
For more information about domain.xml and virtual servers, see the Sun Java System Application Server Reference.
Default Web Modules
You can assign a default web module to the default virtual server and to each new virtual server you create. For details, see Virtual Servers. To access the default web module for a virtual server, point your 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
Configuring Logging in the Web Container
You can configure logging in the web container for the entire server in these ways:
Using ServletsSun Java System 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 will continue to 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
This section describes how to create effective servlets to control application interactions running on a Sun Java System Application Server, including standard servlets. In addition, this section describes the Sun Java System Application Server features to use to augment the standards.
This section contains the following topics:
Handling Threading Issues
By default, servlets are not thread-safe. One way to make a servlet (or a block within a servlet) thread-safe is to use the javax.servlet.SingleThreadModel class to create a single-threaded servlet. When a single-threaded servlet is deployed to the Sun Java System Application Server, the servlet engine creates a servlet instance pool used for incoming requests (multiple copies of the same servlet in memory).
You can change the number of servlet instances in the pool by setting the singleThreadedServletPoolSize property of the sun-web-app element in the sun-web.xml file. For more information on sun-web.xml, see “The sun-web.xml File” on page 151.
A single-threaded servlet is slower under load because new requests must wait for a free servlet instance in order to proceed, but this is not a problem with distributed, load-balanced applications since the load automatically shifts to a less busy process.
Invoking a Servlet with a URL
You can call servlets deployed to the Sun Java System Application Server by using URLs embedded as links in an application’s HTML or JSP pages. The format of these URLs is as follows:
http://server:port/context_root/servlet_name?name=value
The following table describes each URL section.
In this example, localhost is the host name, MortPages is the context root, and calcMortgage is the servlet name:
http://localhost:8080/MortPages/calcMortgage?rate=8.0&per=360&bal=180000
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 start-up 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 in these ways:
Using the Administration Console
Use the Administration Console as follows:
For more information, see the Sun Java System Application Server Administration Guide.
Editing the domain.xml File
Edit the domain.xml file, entering the desired true or false values, then restart the server:
<log-service use-system-logging=true
log-to-console=true />For more information about domain.xml, see the Sun Java System Application Server Reference.
Caching Servlet Results
The Sun Java System 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 Sun Java System Application Server caches the request results for a specific amount of time. In this way, if another data call occurs, the Sun Java System 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, you could cache a high level report showing demographic data taken from quiz results that is updated once an hour.
You can define how a Sun Java System Application Server web application handles response caching by editing specific fields in the sun-web.xml file. In this way, you can create portable servlets that still take advantage of this valuable Sun Java System Application Server feature.
For more information about JSP caching, see JSP Caching.
The rest of this section covers the following topics:
Caching Features
Sun Java System Application Server 8 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. You can override this timeout for an individual cache mapping by specifying the cache-mapping subelement timeout.
- You can determine caching criteria programmatically by writing a cache helper class. For example, if a servlet only 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. See CacheHelper Interface.
- You can determine cache key generation programmatically by writing a cache key generator class. 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:
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.
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 “Caching Elements” on page 168.
CacheHelper Interface
Here is the CacheHelper interface:
package com.sun.appserv.web.cache;
import java.util.Map
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
/** CacheHelper interface is an user-extensible interface to customize:
* a) the key generation b) whether to cache the response.
*/
public interface CacheHelper {
// name of request attributes
public static final String ATTR_CACHE_MAPPED_SERVLET_NAME =
"com.sun.appserv.web.cachedServletName";
public static final String ATTR_CACHE_MAPPED_URL_PATTERN =
"com.sun.appserv.web.cachedURLPattern";
public static final int TIMEOUT_VALUE_NOT_SET = -2;
/** initialize the helper
* @param context the web application context this helper belongs to
* @exception Exception if a startup error occurs
*/
public void init(ServletContext context, Map props) throws Exception;
/** getCacheKey: generate the key to be used to cache this request
* @param request incoming <code>HttpServletRequest</code> object
* @returns the generated key for this requested cacheable resource.
*/
public String getCacheKey(HttpServletRequest request);
/** isCacheable: is the response to given request cachebale?
* @param request incoming <code>HttpServletRequest</code> object
* @returns <code>true</code> if the response could be cached. or
* <code>false</code> if the results of this request must not be cached.
*/
public boolean isCacheable(HttpServletRequest request);
/** isRefreshNeeded: is the response to given request be refreshed?
* @param request incoming <code>HttpServletRequest</code> object
* @returns <code>true</code> if the response needs to be refreshed.
* or return <code>false</code> if the results of this request
* don't need to be refreshed.
*/
public boolean isRefreshNeeded(HttpServletRequest request);
/** get timeout for the cached response.
* @param request incoming <code>HttpServletRequest</code> object
* @returns the timeout in seconds for the cached response; a return
* value of -1 means the response never expires and a value of -2 indicates
* helper cannot determine the timeout (container assigns default timeout)
*/
public int getTimeout(HttpServletRequest request);
/**
* Stop the helper from active use
* @exception Exception if an error occurs
*/
public void destroy() throws Exception;
}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” on page 171.
Here is the CacheKeyGenerator interface:
package com.sun.appserv.web.cache;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
/** CacheKeyGenerator: a helper interface to generate the key that
* is used to cache this request.
*
* Name of the ServletContext attribute implementing the
* CacheKeyGenerator is configurable via a property of the
* default-helper in sun-web.xml:
* <default-helper>
* <property
* name="cacheKeyGeneratorAttrName"
* value="com.acme.web.MyCacheKeyGenerator" />
* </default-helper>
*
* Caching engine looks up the specified attribute in the servlet
* context; the result of the lookup must be an implementation of the
* CacheKeyGenerator interface.
*/
public interface CacheKeyGenerator {
/** getCacheKey: generate the key to be used to cache the
* response.
* @param context the web application context
* @param request incoming <code>HttpServletRequest</code>
* @returns key string used to access the cache entry.
* if the return value is null, a default key is used.
*/
public String getCacheKey(ServletContext context,
HttpServletRequest request);
}About the Servlet Engine
Servlets exist in and are managed by the servlet engine in the Sun Java System 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
After the servlet engine instantiates the servlet, the servlet engine runs its init() method to perform any necessary initialization. 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. 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 Sun Java System 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, collating the information in the request object or in a JDBC ResultSet object, and then passing the newly generated content to a JSP for formatting and delivery back to the user.
Allocating Servlet Engine Resources
By default, the servlet engine creates a thread for each new request. This is less resource intensive than instantiating a new servlet copy in memory for each request. Avoid threading issues, since each thread operates in the same memory space where servlet object variables can overwrite each other.
If a servlet is specifically written as a single thread, the servlet engine creates a pool of servlet instances to be used for incoming requests. If a request arrives when all instances are busy, it is queued until an instance becomes available. The number of pool instances is configurable in the sun-web.xml file, in the singleThreadedServletPoolSize property of the sun-web-app element.
For more information about the sun-web.xml file, see “The sun-web.xml File” on page 151. For more information on threading issues, see Handling Threading Issues.
Using JavaServer PagesSun Java System Application Server 8 supports the following JSP features:
For information about creating JSPs, 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 (JSPs) as page templates in a Sun Java System Application Server web application. This section contains the following topics:
JSP Tag Libraries and Standard Portable Tags
Sun Java System Application Server supports tag libraries and standard portable tags. For more information, see the JavaServer Pages Standard Tag Library (JSTL) page:
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 JavaServer 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 JSP page fragments within the Java engine. Each can be cached using different cache criteria. For example, suppose you have page fragments to view stock quotes, weather information, and so on. The stock quote fragment can be cached for 10 minutes, the weather report fragment 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 description file is in this JAR file.
To allow all web applications to share this tag library, change the following element in the domain.xml file:
<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>
For more information about the domain.xml file, see the Sun Java System Application Server Reference.
You refer to these tags in your 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>.
If you wish to use a different URI for this tag library, you can use an explicit <taglib> element in your web.xml file.
The tags are as follows:
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.
Example
The following example represents a cached JSP page:
<%@ taglib prefix="mypfx" uri="Sun ONE Application Server Tags" %>
<%
String cacheKey = null;
if (session != null)
cacheKey = (String)session.getAttribute("loginId");
// check for nocache
boolean noCache = false;
String nc = request.getParameter("nocache");
if (nc != null)
noCache = "true";
// force reload
boolean reload=false;
String refresh = request.getParameter("refresh");
if (refresh != null)
reload = true;
%>
<mypfx:cache key="<%= cacheKey %>" nocache="<%= noCache %>" refresh="<%= reload %>" timeout="10m">
<%
String page = request.getParameter("page");
if (page.equals("frontPage") {
// get headlines from database
} else {
.....
%>
</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.
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>Compiling JSPs: The Command-Line Compiler
Sun Java System Application Server provides the following ways of compiling JSP 2.0 compliant source files into servlets:
- JSPs are automatically compiled at runtime.
- The asadmin deploy command has a precompilejsp option; see “asadmin deploy” on page 107.
- The sun-appserv-jspc Ant task allows you to precompile JSPs; see “sun-appserv-jspc” on page 125.
- The jspc command line tool, described in this section, allows you to precompile JSPs at the command line.
The jspc command line tool is located under install_dir/bin (make sure this directory is in your path). The format of the jspc command is as follows:
jspc [options] file_specifier
The following table shows what file_specifier can be in the jspc command.
The following table shows the options for the jspc command.
For example, this command compiles all the JSP files in the web application under webappdir into class files under webappdir/classes and creates the web.xml file:
jspc -d webappdir/classes -webapp webappdir -webxml web.xml
To use these precompiled JSPs in a web application, put the classes under webappdir/classes into a JAR file, and place the JAR file under WEB-INF/lib.
The presence of both the precompiled classes and the servlet mappings in web.xml prevents the JSP compiler from being invoked when the web application is invoked.
Creating and Managing User SessionsThis 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
You can configure whether and how sessions use cookies and URL rewriting by editing the session-properties and cookie-properties elements in the sun-web.xml file for an individual web application. See “session-properties” on page 161 and “cookie-properties” on page 162 for more about the properties you can configure.
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.
Sun Java System Application Server gives you 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 memory Persistence Type
This persistence type is not designed for a production environment. 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 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.
<sun-web-app>
...
<session-config>
<session-manager persistence-type=memory>
<manager-properties>
<property name="reapIntervalSeconds" value="20" />
</manager-properties>
</session-manager>
...
</session-config>
...
</sun-web-app>The memory persistence type supports all the manager properties listed under “manager-properties” on page 159.
For more information about the sun-web.xml file, see “The sun-web.xml File” on page 151.
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.
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.
<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” on page 159 except sessionFilename, and the directory store property listed under “store-properties” on page 160.
For more information about the sun-web.xml file, see “The sun-web.xml File” on page 151.