How A web.xml Or Deployment Descriptor Works | FAQ

A deployment descriptor is an XML file that contains configuration information used by the Web application for execution on the Servlet engine. The deployment descriptor for a Web application is the <TOMCAT_HOME>/webapps/<webappname>/WEB-INF/web.xml file. There is another web.xml file that is applicable for all Web applications deployed in the servlet Engine, and this is located under <TOMCAT_HOME>/conf . This section examines application-specific deployment only. However, the configuration-related information is valid for all deployment descriptors.

The Servlet 2.5 specification uses a schema for the deployment descriptor — older specifications (Servlet 2.3 and earlier) still use a Document Type Definition (DTD). Both are still supported for backward compatibility with existing Web applications. Because you might need to support existing Web applications, we will cover both the older Servlet 2.3–style web.xml and the schema-based versions. The first few lines of the deployment descriptor indicate whether it is the Servlet 2.4/2.5 schema-based web.xml or the older DTD-based version. Following is a Servlet 2.3 DTD-based web.xml :

<?xml version=”1.0″ encoding=”ISO-8859-1″?>

<!DOCTYPE web-app

PUBLIC “-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN”

“http://java.sun.com/dtd/web-app_2_3.dtd”>

<web-app>

…

</web-app>

Following is a Servlet 2.4 schema-based web.xml :

<?xml version=”1.0″ encoding=”ISO-8859-1″?>

<web-app xmlns=”http://java.sun.com/xml/ns/j2ee”

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee web-app_2_4.xsd”

version=”2.4″>

…

</web-app>

Finally, the new Servlet 2.5 schema-based web.xml is as follows:

<?xml version=”1.0″ encoding=”ISO-8859-1″?>

<web-app xmlns=”http://java.sun.com/xml/ns/j2ee”

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee

http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd”

version=”2.5″>

…

</web-app>

If you use a Servlet 2.3–type deployment descriptor, Tomcat ignores all the new Servlet and JSP features

that you use in your application, such as JSP EL (Expression Language).

The Servlet 2.3–Style Deployment Descriptor

The web.xml file takes the following generalized form:

<?xml version=”1.0″?>

<!DOCTYPE web-app

PUBLIC “-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN”

“http://java.sun.com/j2ee/dtds/web-app_2_3.dtd”>

<web-app>

<icon>

<display-name>

<description>

<distributable>

<context-param>

<filter>

<filter-mapping>

<listener>

<servlet>

<servlet-mapping>

<session-config>

<mime-mapping>

<welcome-file-list>

<error-page>

<taglib>

<resource-env-ref>

<resource-ref>

<security-constraint>

<login-config>

<security-role>

<env-entry>

<ejb-ref>

<ejb-local-ref>

</web-app>

The order of elements inside the <web-app > element must be as shown previously, but some elements are optional, and others may appear multiple times. The following table may be used as a quick reference to the functionality of each element.

In the following sections, you examine a minimal web.xml file to understand what must be present.

The XML Header

Every web.xml file complies with the XML specifications that require an XML header in the beginning of the file, as shown here:

<?xml version=”1.0″?>

Optionally, the declaration may also include an encoding type that identifies the character encoding of the document, as is standard for XML. For example, if the document is encoded in UTF-8, the declaration may be provided as follows:

<?xml version=”1.0″ encoding=”UTF-8″?>

The DTD Declaration

The next tag is a Document Type Definition (DTD) tag. A DTD is a document that outlines the structure of the web.xml elements, what elements are allowed and in which order, and their content. The inclusion of a standard DTD declaration in our web.xml file looks as follows:

<?xml version=”1.0″?>

<!DOCTYPE web-app

PUBLIC “-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN”

“http://java.sun.com/dtd/web-app_2_3.dtd”>

Applications that comply with the Servlet specifications prior to 2.3, such as Tomcat 3 web.xml files, for example, will have the following DTD reference:

<!DOCTYPE web-app

PUBLIC “-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN”

“http://java.sun.com/j2ee/dtds/web-app_2_2.dtd”>

Backward compatibility is required as per the Servlet 2.3 specifications, so applications that were written for the Servlet 2.2 specifications will work unaltered on Tomcat 6, except for any dependencies on the exact configuration of the server (such as the location of databases, network authentication, and the name of the server and the host). Because the Servlet 2.3 specifications have introduced a number of new tags since 2.2, we will also highlight these tags where appropriate.

<web-app>

The root element of the web.xml file is <web-app> , and all other XML elements reside inside it:

<?xml version=”1.0″?>

<!DOCTYPE web-app

PUBLIC “-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN”

“http://java.sun.com/dtd/web-app_2_3.dtd”>

<web-app>

</web-app>

This is all that is required for the web.xml file to be complete. However, in many practical cases, there will be more. Let’s begin by covering elements that describe the application. A number of elements are provided so that deployment tools can identify Web applications visually and textually.

<icon>

This tag holds the location of the image files within the Web application that may be used by a tool to represent the Web application visually. The <icon> tag may contain two child elements ( <small-icon> and <large-icon> ) that carry the location of a 16 × 16–pixel image file and a 32 × 32–pixel image file, respectively.

<icon>

<small-icon>/images/icons/exampleapp_small.gif</small-icon>

<large-icon>/images/icons/exampleapp_large.gif</large-icon>

</icon>

<display-name>

This tag provides a name that can be used for display in a GUI. The name need not be unique. For example, the following display name is typical:

display-name>Example Application</display-name>

<description>

This tag contains the description of a Web application, as shown in the following example:

<?xml version=”1.0″?>

<!DOCTYPE web-app

PUBLIC “-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN”

“http://java.sun.com/dtd/web-app_2_3.dtd”>

<web-app>

<icon>

<small-icon>/images/icons/exampleapp_small.gif</small-icon>

<large-icon>/images/icons/exampleapp_large.gif</large-icon>

</icon>

<display-name>Wrox Example Application</display-name>

<description>

Application contains a number of simple resources for illustrating configuration points.

</description>

</web-app>

These element tags must be listed in the same order as shown earlier in the section (refer to http://

java.sun.com/dtd/web-app_2_3.dtd for more information). The actual number of tools for

deploying Web archives (especially in a drag-and-drop manner as suggested by the use of icon files) is

somewhat low, so it is common for these values not to be provided. The web.xml file may be heavily

commented. XML comments take the same form as HTML ones:

<!–

This is a comment

–>

<distributable>

This tag describes a Web application that is designed to be distributable for load balancing and fail-over.

By default, the value of this is false .

<context-param>

Context parameters are mechanisms used for setting application-initialization parameters. For example,

you could set the URL to a database here. The following example enables the administrator to change the

title and greeting of the example application:

<context-param>

<param-name>title</param-name>

<param-value>Wrox example application – Chapter 7</param-value>

</context-param>

<context-param>

<param-name>greeting</param-name>

<param-value>Welcome to the example application</param-value>

</context-param>

There may be any number of context parameters in the application, known as initial parameters . Each dynamic resource (such as a servlet, a JSP page, or a class) with access to the application context is able to look up the value associated with a given parameter name. Typical items provided as a context parameter are the debug status of the application, the verbosity of logging (these two are often interlinked), and as much other externalized configuration as the application developer has allowed.

<filter>

Filters are new to the Servlet 2.3 specifications. Filters are reusable components that intercept the client request and response and apply some type of processing to them. For example, a filter may apply compression to the contents of the response, thus reducing bandwidth usage and improving the performance of the application by minimizing the size of the response packet. This is just an example, of course, and to make it work in a real-world situation would require additional support in the browser. Filters are intended to be the ultimate reusable Web components. They should be virtually independent of the content being created. Examples include the compression filter, a transformation filter that may convert XML to HTML or WML, a filter to provide the logging of resource usage, and a filter to restrict access to resources.

A filter, like all Web application resources, can be mapped to a URL pattern, including the extension of the resource, a section of the site (such as everything within the images directory), or even a URL alias such as the servlet alias that exists on most default installations of Java Web servers.

In addition, filters can have an icon associated with them, and configuration parameters (initialization parameters). An example configuration is shown here:

<filter>

<icon>/images/icons/filter.jpg</icon>

<filter-name>Compressor</filter-name>

<display-name>Compression Filter</display-name>

<description>This filter applies compression</description>

<filter-class>com.wrox.utils.CompressionFilter</filter-class>

<init-param>

<param-name>compression_type</param-name>

<param-value>gzip</param-value>

</init-param>

</filter>

Once a filter is defined, it can be mapped against any number of URL patterns. In addition, when many filters are defined for a given URL pattern, they are all applied in the order in which they are defined in the web.xml file. In the following example, the compression filter is applied to every URL:

<filter-mapping>

<filter-name>Compressor</filter-name>

<url-pattern>*</url-pattern>

</filter-mapping>

<listener>

Listeners are designed to respond to events in an application. For example, a JavaBean could send an e-mail when an event requiring administration is recorded:

<listener>

<listener-class>com.wrox.listeners.ExampleListener</listener-class>

</listener>

<servlet>

A servlet is declared in the web.xml file by assigning it a unique name, which references its fully qualified name against a shorter, more intuitive name:

<servlet>

<icon>/images/icons/DownloadServlet.jpg</icon>

<servlet-name>Download</servlet-name>

<display-name>File Download Servlet</display-name>

<description>

This Servlet manages file downloads in the application

</description>

<servlet-class>com.wrox.servlets.DownloadServlet</servlet-class>

<!– require terms and conditions agreement? –>

<init-param>

<param-name>require_tc</param-name>

<param-value>true</param-value>

</init-param>

<load-on-startup>5</load-on-startup>

<!– uncomment this if Servlets must run in user role

<run-as>

<description>

This Servlet does not require authorization to resources

</description>

<role-name>admin</role-name>

</run-as>

–>

</servlet>

In the preceding example, the servlet manages the download process, enabling you to decide at runtime

if a user is required to sign a terms and conditions acceptance form before download commences. The

optional <icon> , <display-name> , and <description> elements work in the same way as described

previously. The fully qualified name of the servlet is specified in the <servlet-class> element.

Because JSP pages are ultimately compiled into servlets, an alternative to the servlet class name

( <servlet-class> element) is to specify the JSP file name ( <jsp-file> element) to which these configuration

parameters should be applied, thus making JSP files fully configurable. The reference is a full

path, from the root of the application to the JSP file, as shown in the following example:

<servlet>

<servlet-name>ExampleJSP</servlet-name>

<jsp-file>/admin/users/ListAllUsers.jsp</jsp-file>

<!– list disabled user accounts –>

<init-param>

<param-name>list_disabled_accs</param-name>

<param-value>false</param-value>

</init-param>

</servlet>

The initialization parameters work in the same way as the application context parameters do. However, they are specific to the servlet. The <load-on-startup> element specifies an integer value indicating whether the servlet must be

loaded when the Tomcat server boots, rather than on a client’s request. If this value is not specified or it is negative, the container loads the servlet into memory when the first request comes in. If the value is zero or a positive integer, the container must load the servlet into memory at startup of the Web application. Servlets assigned lower integers are loaded before those with higher integers. Servlets with the same <load-on-startup> values are loaded in an arbitrary sequence by the container. In the Download Servlet example, the <run-as> attribute is not specified because it is commented out. However, if the servlet requires a privileged role, it can be specified here, so that any resource requiring a privileged user will discover it while calling the isUserInRole() method.

<session-config>

Session configuration enables sessions to be configured for every application. The <session-timeout> element can be used to set a session timeout value. This value can be calculated by considering typical client usage patterns, along with security requirements. For example, if a user is asked to enter a great deal of information, the session timeout value may be set to a larger number to avoid information being lost. Alternatively, in low-security environments with serializable sessions, it is possible to set sessions to never expire so that the user is always recognized.

The session configuration is defined as follows:

<session-config>

<session-timeout>40</session-timeout>

</session-config>

If the value is zero or less, the session is never expired and the application must explicitly remove it as required. If the element is not provided, the default value of 30 is used as specified in the global web.xml file within Tomcat’s <TOMCAT_HOME>/conf directory.

<mime-mapping>

MIME types enable browsers to recognize the file type of the content being returned by the server so that the browser can handle it correctly, to determine whether to display it (as HTML, plain text, images); pass the content to a plug-in (such as Flash); or prompt the user to save the file locally. Tomcat comes preconfigured with the majority of MIME mappings set, which can be seen in the <TOMCAT_HOME>/conf/web.xml file. MIME mappings set in this file apply to all applications. Additional MIME mappings may be configured on each Web application with the <mime-mapping> element. This can be especially useful when the developer defines new extensions to suit the application. In addition, this can be useful if you wish to have a certain MIME type treated differently from the way it would normally be treated. For example, for a content management application, you may want to prevent Internet Explorer from recognizing the MIME type and thus opening the file in the appropriate application, and instead prompt the user with the File Save dialog box. Another example might be the automatic generation of Excel files. Excel will accept comma-separated values and convert them to an Excel spreadsheet if the MIME type sent to Internet Explorer is set to the Excel MIME type of application/x-excel or application/ms-excel . This will open Excel, although the file is a CSV file. This technique is used in Web applications for non-integrated applications in which a company administrator wants to be able to dynamically generate Excel files from a site into their reports, because creating Excel sheets on-the-fly is quite complex.

This is a common technique when it is desirable to use an external application to view content from a Web application/script. The following example shows how the Excel-CSV MIME mapping is done:

<mime-mapping>

<extension>csv</extension>

<mime-type>application/x-msexcel</mime-type>

</mime-mapping>

…

<welcome-file-list>

Sometimes a request is made from a client to an application without a definite resource specified in the

URL. For example, the root of the application is requested as follows:

http://localhost:8080/exampleapp/

whereas a definite resource is requested as shown in the following URL:

http://localhost:8080/exampleapp/whatsnew.jsp

In such cases, the Web application looks for a file called index.jsp in the Web application’s directory

and executes this file if it exists. If this file cannot be found, it looks for index.htm and index.html in

turn. This is because the welcome file list defined in <TOMCAT_HOME>/conf/web.xml includes these files

by default. If the web.xml file in the WEB-INF directory of your Web application does not mention a welcome

file list, the default is used.

The format for the welcome file list is as follows (this will apply to each request that does not specify a

resource). This means that each of the subdirectories within the application root will also have this rule

applied to it. In the following example, default.jsp will be loaded instead of index.jsp :

<welcome-file-list>

<welcome-file>default.jsp</welcome-file>

<welcome-file>default.htm</welcome-file>

<welcome-file>UserWelcome.jsp</welcome-file>

</welcome-file-list>

Note that if none of the files in the example list are found, then, depending on the configuration, an

HTTP 404–Not Found error message is displayed.

<error-page>

The default behavior for Web applications written in JSP is to return a stack trace , which is a complex view into the internals of the virtual machine that greatly reduces the user-friendliness of the application. You can configure error pages to provide a user-friendly mechanism for informing users about a problem, enabling them to continue using the application. The errors are mapped to the HTTP specification error mappings (such as a code for a resource that cannot be found, server malfunctioning, authentication issues, resource issues, and so on).

In addition, because there are no one-to-one correspondences between HTTP errors and Java exceptions, the exception class type may be specified. This enables the creation of error pages that are generic, and follows good programming practice. Someone without an understanding of the application’s internals can configure them. Following is an example for the common 404 message for a NullPointerException :

<error-page>

<error-code>404</error-code>

<location>/errors/oops.jsp</location>

</error-page>

<error-page>

<exception-type>java.lang.NullPointerException</exception-type>

<location>/errors/badlycodedpage.jsp</location>

</error-page>

Like the JSP page example, <location> must be a reference from the root of the application.

These pages often have a message that notifies the user of the problem, and provisionally provides both a search box so that users can locate the resources they need and a list of likely links in the site from which they might receive help.

Often the problem is a configuration issue, and users are best served by being informed that the problem will be fixed and they should return later. The developer may be informed through automated parsing of error logs or through a notification system that sends e-mails to a watched e-mail address or directly to the administrator or the development team. Should any problem occur in a page (such as missing resources, a bug in the software, or parts of the system being down), a page configured here would be returned. Error pages can also be written so that they display contextual information (that relates to the specific problem at hand), but this requires an understanding of the inner workings of the system and can only be provided by a developer.

HTTP return codes can be found at the following URL:

www.w3c.org/Protocols/HTTP/HTRESP.html

Error pages are configured by associating them with the HTTP return code that covers the error group. Two examples are provided in the following example, one for the HTTP 404 code and one for a NullPointerException (an internal error that is often hard to debug in an application and may require a developer’s intervention to correct):

<error-page>

<error-code>404</error-code>

<location>/errors/ResourceNotFound.htm</location>

</error-page>

<error-page>

<exception-type>java.lang.NullPointerException</exception-type>

<location>/errors/ApplicationProblem.jsp</location>

</error-page>

<taglib>

Tag libraries are reusable Java components that may be invoked using markup tags in the page. The tag library definition is specified by the application developer and the HTML designers. However, the main configuration of these reusable components is done in a separate file (one with a .tld extension), as this entry simply enables aliasing of the location of this configuration document against a URI. The exact location of the configuration file, which is given as a reference

to the file from the Web application’s root directory, can then be referred to by its alias. This aliasing enables location-independence (that is, the tag library configuration files can be moved around without editing the JSP pages that refer to the tag library configuration file, so long as the tag entry points to it). An example entry is shown here:

<taglib>

<taglib-uri>applicationtags.tld</taglib-uri>

<tablib-location>/WEB-INF/tlds/web-app.tld</taglib-location>

</taglib>

In this example, the tag library configuration file that the Web application container needs for resolving references, looking up initialization parameters, and enforcing proper use of the tags is referred to by its alias, applicationtags.tld . The location of the configuration file is customarily within the WEB-INF directory in a directory called tlds . If this location is changed, you must adjust the <taglib-location> entry, but any code referencing it can stay the same.

<resource-ref>

Two elements, <resource-ref> and <resource-env-ref> , are provided for configuring resources for a Web application environment. These elements enable two things:

❑ The management of connections to resources, such as a reference to the object pooling resource connection (much like database-connection pooling), to make the process more efficient:

Object pooling enables efficient use of resources by defining a component that manages connections to those resources. In the case of databases, the pool will make a number of connections and when a client requests one, it is handed over to the client to be used. When the client requests the connection to be closed, the pool retrieves the connection, but rather than closing it and establishing a new connection, it reuses the connection by handing it over to the next client

(as long as the authority constraints and the type of connection matches). Because establishing a connection to a database is a resource-intensive process, this can affect application performance. A pool can also be configured to refresh the connections periodically and to restore dropped connections so that the application can efficiently recover from database failures.

❑ A reference to administered objects, which provides the application with access to runtime administration of the resource: Administered objects enable the application configuration to be changed without restarting the server. They can also be used to monitor the state of the application by interrogating administered objects for their current state.

<security-constraint>

Web resources may be associated with some security constraints for authentication purposes. The constraints limit access to the resource according to user roles (such as manager, administrator, user, and guest) and by transport guarantee (which can include SSL secure data transmission), guaranteeing delivery and non-interference. The <security-constraint> element enables a Web resource to be defined against an authentication constraint and a user data constraint.

An entry takes the following form:

<security-constraint>

<display-name>Name String</display-name>

<web-resource-collection>

<web-resource-name>GETServlet</web-resource-name>

<description>

Group together all Servlet GET requests on the server using

/servlet/servletname. We are grouping these requests as (we have

decided) they require additional security being inherently less secure

than the POST method and aliased Servlet calls.

</description

<url-pattern>/servlet/*</url-pattern>

<http-method>GET</http-method>

</web-resource-collection>

<auth-constraint>

<description>

All roles are constrained to secure connection to Servlet resource

via GET calls

</description>

<role-name>*</role-name>

</auth-constraint>

<user-data-constraint>

<description>

Constrain the user data transport for GET Servlet requests to secure

sockets

</description>

<transport-guarantee>INTEGRAL</transport-guarantee>

</user-data-constraint>

</security-constraint>

<web-resource-collection>

The <web-resource-collection> element identifies a group of resources and the methods by which these resources can be requested. In the previous example, all Servlets identified by the pattern /servlet can be accessed via the HTTP GET method. Any number of URL patterns and valid HTTP methods may be provided to exactly define the resource collection.

<auth-constraint>

The <auth-constraint> element uses role-based authentication to constrain access to Web resources. You can limit groups of users to whom this security constraint is applied to using role-based authentication. Therefore, placing administrator in the <role-name> tag — for example, as <rolename> administrator</role-name> — allows only users belonging to that role to access the servlets.

Valid values are specified by the developer of the application. In the preceding example, <rolename>*</role-name> indicates that all roles should be allowed access. An empty element indicates that no roles should be allowed access to the resource. There is no constraint on the number of <role-name> elements required to define security constraints. If none are provided, then the resource is unavailable as no authentication is possible. You might make resources unavailable for security reasons by removing all references to <role-name> elements in the web.xml file and then restarting Tomcat.

<user-data-constraint>

The <user-data-constraint> element indicates what guarantees are given about the communication of data from and to the client. A value of NONE indicates that no guarantees are provided that the data has not been tampered with or intercepted by anyone other than the client and the system (the server). Conversely, a value of INTEGRAL guarantees the authenticity of the data — i.e. that the data has not been interfered with — whereas CONFIDENTIAL guarantees that the data has not been intercepted by a third party. Specifying INTEGRAL or CONFIDENTIAL means that SSL will be used by redirecting the client to the SSL port of the server. This type of configuration is likely to be defined at design time. However, in a well-designed application, it is up to the deployment engineer/system administrator to follow the design architecture to enforce the security constraints defined within it. This enables authentication requirements to be absent from the application code itself, thus allowing the application to be very flexible so that it can be configured as business needs dictate.

<login-config>

This element relates to the configuration of login authentication in the application. The <login-config> element contains the authentication method, the Realm name and login page, and the authentication error page that should be used if form-based authentication is specified:

<login-config>

<auth-method>FORM</auth-method>

<realm-name>MemoryRealm</realm-name>

<form-login-config>

<form-login-page>login.jsp</form-login-page>

<form-error-page>notAuthenticated.jsp</form-error-page>

</form-login-config>

</login-config>

The authentication method consists of the HTTP methods available — namely, BASIC , DIGEST , FORM ,and CLIENT-CERT . These correspond to basic authentication (plain text), digest (base64-encoded responses), FORM -based authentication (which enables an HTML page with a form that prompts the user to log in and returns the username and password), and client-certificate–based authentication, respectively. The <realm-name> identifies the Realm that the server should use to authenticate the user against — in our example, the Realm name alludes to the file-based list of users and passwords provided by the memory Realm with Tomcat. In a production environment, using the memory Realm is not recommended.

Instead, a JDBC or JDNI Realm is far more robust and maintainable. Having chosen form-based authentication, we must specify the login page and the error page, in case a login fails. In this case, we have specified that login.jsp contains the login request form. Bad authentication requests are redirected to notAuthenticated.jsp .

<security-role>

Security roles were discussed briefly earlier in the chapter. The <security-role> element enables roles to be defined along with the optional description:

<security-role>

<description>

Administrator of the application is allowed read/write rights to the content

</description>

<role-name>administrator</role-name>

</security-role>

<env-entry>

The <env-entry> element is used to declare environment entries. These are JNDI value parameters that can be used to configure the application. Unlike context initialization parameters, these values are dynamic. They can be referred to and updated at runtime so that the application can be reconfigured dynamically and resources outside the Web application can access them. In particular, they can be administered by non-Java application components and can be managed as part of the entire enterprise administration system.

This works like all JNDI resources; the parameter is referenced from the JNDI initial context and can be accessed using the java:comp/env environment naming context. The env-entry is defined as relative to this context.

The environment entry must be typed to a Java data type (such as String or Integer) so that it can be used within the application and can be used to define environment limits (such as minimum and maximum values). The general structure of an environment entry is as follows:

<env-entry>

<description>Lower limit – minimum allowable value</description>

<env-entry-name>MinimumValue</env-entry-name>

<env-entry-value>5</env-entry-value>

<env-entry-type>java.lang.Integer</env-entry-type>

</env-entry>

Environment entries are usually specific to the environment in which they are operating (that is, they are application-specific). However, accepted norms for resource naming may be adopted in an attempt to harmonize resource configuration.

The value can then be accessed using code fragments such as the following:

/* Create a lock for context retrieval */

private final Object lock = new Object();

…

synchronized (lock) {

/* Obtain the initial context */

Context initCtx = new InitialContext();

Context envCtx = (Context) initCtx.lookup(“java:comp/env”);

// Look up environment entry

Integer minValue = (Integer)envCtx.lookup(“MinimumValue”);

} /* End lock */

In this code example, the call to get the JNDI Initial Context and do a lookup for the java:comp/env context is inside a synchronized block because it is not thread-safe.

The Servlet 2.4/2.5–Style Deployment Descriptor

Because the Servlet 2.5 and 2.5 style deployment descriptors are very similar to each other, they are covered together. In the web.xml schema, the web-app element is the root element for the deployment descriptor, and all

other elements are contained within it. Unlike the DTD-style 2.3 Deployment Descriptor, the enclosed elements can be in any order.

These elements are listed in the following table. Except for session-confi g , jsp-confi g , and loginconfig , all other elements can occur multiple times in the web.xml file.

The following sections describe these elements in more detail.

web-app

In the new web.xml schema, the web-app element is the root element for the deployment descriptor.

A sample web-app element for Servlet 2.5 is shown here:

<web-app xmlns=”http://java.sun.com/xml/ns/j2ee”

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee

http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd”

version=”2.5″>

…

</web-app>

New in Servlet 2.5: The optional full attribute in the web-app element. The web-app element for Servlet 2.5 has an optional attribute called full . Setting full to true (the default is false ) causes the Servlet container to ignore any annotations in the class files of the Web application. Annotations are new in Java SE 5; they allow Java programs to embed special configuration information, instead of specifying it in configuration files.

If no annotations are used by the Web application, then the full attribute should be used to tell the container not to do these checks while loading up the Java classes.

An example of the web-app element with the full attribute is shown here.

The description element provides a textual description for its parent element. When included under the web-app element (as shown in the “JSP examples” section of the Web application included in the Tomcat distribution), it describes the Web application. This element is used elsewhere, too (for example, inside the context-param and filter elements), where it provides a description for each element:

<description>

JSP 2.0 Examples

</description>

The description element has an optional attribute, xml-lang , which indicates the language of the description text. This defaults to en for English. There can also be multiple description elements, usually with different xml-lang attributes, to support localization.

display-name

The display-name element gives a short, descriptive name for the parent element. For example, when used directly under the web-app element, it provides a name for the Web application. This name is displayed by software tools that work with deployment descriptors. Like the description element, the display-name element too has an xml-lang attribute (which defaults to en ) to indicate the language; and multiple display-name elements with different xml-lang values can be used to handle multiplelanguage support. A sample display-name element is shown here:

<display-name xml-lang=”en”>JSP 2.0 Examples</display-name>

distributable

The presence of a distributable element indicates that the Web application has been programmed to be deployed (if required) in a distributed Servlet container. Such a Servlet container may distribute the Web application to multiple JVMs for scalability or performance considerations.

<distributable/>

ejb-local-ref

The ejb-local-ref element declares a reference to the enterprise bean’s (EJB) local home. This element has the following child elements:

❑ ejb-ref-name : The EJB reference name

❑ ejb-ref-type : The EJB reference type

❑ ejb-link : Specifies that the EJB reference is linked to an enterprise bean

❑ local : The fully qualified name of the EJB’s local interface

❑ local-home : The fully qualified name of the EJB’s local home interface

ejb-ref

This element contains a reference to an EJB’s home. It has the following child elements:

❑ ejb-refname : The name used in the deployment component to refer to the EJB

❑ ejb-ref-type : Type of the EJB (Entity/Session)

❑ home : Fully qualified name of the EJB’s home interface

❑ remote : Fully qualified name of the EJB’s remote interface

❑ ejb-link : Specifies that the EJB reference is linked to an enterprise bean

❑ description : A text description of the EJB reference

A sample ejb-ref element is shown here:

<ejb-ref>

<description>Employee bean/description>

<ejb-ref-name>EmployeeBean</ejb-ref-name>

<ejb-ref-type>Session</ejb-ref-type>

<home>com.foobar.employee.EmployeeHome</home>

<remote>com.foobar.employee.Employee</remote>

</ejb-ref>

env-entry

The env-entry element declares environment parameters for a Web application. Each env-entry has

the following child elements:

❑ env-entry-name : The JNDI name of the deployment component’s environment entry. This

name is relative to the java:comp/env context, and must be unique within a context.

The error-page element specifies the mapping between an error code or Java exception type and a Web resource. It contains the following child elements:

❑ error-code : The HTTP error code.

❑ exception-type : The fully qualified class name of the Java exception type. Either the error-code or the exception-type should be specified in an error-page element, but not both.

❑ location : The location of the resource (that is, the error Web page) that handles the error. The location is relative to the root of the Web application, and must have a leading slash ( / ).

A sample error-page is shown in the following code:

<error-page>

<error-code>404</error-code>

<location>/myApp/jsp/notFound.jsp</location>

</error-page>

<error-page>

<error-code>500</error-code>

<location>/myApp/jsp/SystemErr.jsp</location>

</error-page>

filter

The filter element declares a filter in the Web application. Filters are Java classes that implement a specified servlet interface ( javax.servlet.Filter ) and provide useful functionality to a Web application. As the name suggests, they are used to “filter” the request before the Web application sees it, or the response before the client sees it. This allows them to be used for applications such as the following:

❑ Logging

❑ Compression (images, data)

❑ Authentication

❑ Encryption

❑ Caching

❑ Transforming content (for example, XML content using XSLT)

The filter is mapped to either a servlet or a URL pattern in the filter-mapping element, using the filter-name value as a reference key.

The filter element consists of the following subelements:

❑ filter-name : The name of the filter. This must be unique in the Web application, and should not be empty. This name must match the filter-name filter-mapping element described in the next section.

❑ filter-class : The fully qualified Java class name of the filter.

❑ init-param : Initialization parameters for the filter specified as name-value pairs. These have the same structure as the context-param element described earlier, and consist of the param-name , param-value , and description subelements.

❑ description : A text description of the filter.

❑ display-name : A short, descriptive name that can be used by tools while displaying the filter configuration.

❑ icon : The icon element specifies icons that can be used by tools to symbolically represent the filter in GUI tools. It has two subelements: a small-icon and large-icon

A sample filter configuration is shown in the following example:

<filter>

<filter-name>Compression Filter</filter-name>

<filter-class>compressionFilters.CompressionFilter</filter-class>

<init-param>

<param-name>compressionThreshold</param-name>

<param-value>10</param-value>

</init-param>

<init-param>

<param-name>debug</param-name>

<param-value>0</param-value>

</init-param>

</filter>

<filter>

…

</filter>

filter-mapping

As specified earlier, the filter is mapped to either a servlet or a URL pattern in the filter-mapping element, using the filter-name value for reference. The Compression Filter was declared in the filter element in the previous example, and the following example shows it being mapped to URL

patterns that begin with /CompressionTest :

<filter-mapping>

<filter-name>Compression Filter</filter-name>

<url-pattern>/CompressionTest</url-pattern>

</filter-mapping>

The filter-mapping element can contain the following subelements:

❑ filter-name : The filter name. This must match the filter-name specified in the filter

element.

❑ url-pattern : The URL pattern to which the filter applies.

New in Servlet 2.5: The dispatcher element.

❑ dispatcher : The dispatcher element indicates what kind of requests the filter is applied to. It can take the values REQUEST , FORWARD , INCLUDE , or ERROR (or a combination). The REQUEST value indicates that the filter is to be applied to requests that come directly from the client. The FORWARD value is for requests that come via a “forward” call. INCLUDE is for “included” Web pages. Finally, the ERROR filter applies if the request is being processed with the error page mechanism (see the error-page element).

❑ servlet-name : The servlet to which the filter applies. Servlet 2.4 allowed either url-pattern or servlet-name , but not both. In Servlet 2.5, both are allowed.

Previously in Servlet 2.4 wildcards were not permitted in the filter mapping. Servlet 2.5 now allows wildcards, enabling you to do something like this:

<filter-mapping>

<filter-name>Logging Filter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

In the previous example, the Logging filter is applied to all servlets and static content because the /* wildcard matches everything.

As mentioned earlier, Servlet 2.5 allows for multiple servlet-name and url-pattern mappings. The Servlet container handles this by internally expanding these mappings into multiple filter-mapping declarations. The example taken from the Servlet 2.5 specifications illustrates this:

<filter-mapping>

<filter-name>Multiple Mappings Filter</filter-name>

<url-pattern>/foo/*</url-pattern>

<servlet-name>Servlet1</servlet-name>

<servlet-name>Servlet2</servlet-name>

<url-pattern>/bar/*</url-pattern>

</filter-mapping>

This is equivalent to specifying four mappings one after the other, as shown here:

<filter-mapping>

<filter-name>Multiple Mappings Filter</filter-name>

<url-pattern>/foo/*</url-pattern>

</filter-mapping>

<filter-mapping>

<filter-name>Multiple Mappings Filter</filter-name>

<servlet-name>Servlet1</servlet-name>

</filter-mapping>

<filter-mapping>

<filter-name>Multiple Mappings Filter</filter-name>

<servlet-name>Servlet2</servlet-name>

</filter-mapping>

<filter-mapping>

<filter-name>Multiple Mappings Filter</filter-name>

<url-pattern>/bar/*</url-pattern>

</filter-mapping>

icon

The icon element specifies icons that can be used by GUI tools to symbolically represent the parent element. It can occur under the web-app element (specifying icons to represent the Web application) or other elements (for example, the filter element described earlier). It has two subelements:

❑ small-icon

❑ large-icon

These set the small and large icon images, respectively. The images are relative path names to gif or jpeg files. The following is an example icon element:

<icon>

<small-icon>an-icon16x16.jpg</small-icon>

<large-icon>an-icon32x32.jpg</large-icon>

</icon>

jsp-config

The jsp-config element is used to configure JSP files in the Web application. It has the following child elements:

❑ taglib : Configures tag libraries used within the JSP pages. This is done via its two child elements: taglib-uri and the taglib-location (the location of the tag configuration .tld file).

❑ jsp-property-group : Configures JSP pages. This in turn has a number of child elements of its own:

❑ url-pattern : The URL pattern for the JSPs.

❑ el-ignored : Sets the isELIgnored property for JSP pages. EL evaluation is enabled by default. JSP EL is a new expression language for accessing data from JSP pages.

❑ page-encoding : The encoding to be used for the page (for example, ISO-8859-1).

❑ scripting-invalid : Used to disable scripting in JSP pages (enabled by default).

❑ is-xml : If true , implies that the documents matching the pattern are JSP pages, and can be interpreted as XML.

❑ include-prelude : Specifies the path to a Web resource to be included in the beginning of the JSP page.

❑ include-coda : Specifies the path to a Web resource to be included at the end of the JSP page.

❑ description : A text description of the filter.

❑ display-name : A short, descriptive name that can be used by tools while displaying the filter configuration.

❑ icon : The icon element specifies icons that can be used by GUI tools to symbolically represent the filter. It has two subelements: a small-icon and large-icon

The jsp-config element for the example JSPs bundled along with Tomcat is shown here:

<jsp-config>

…

<taglib>

<taglib-uri>

http://jakarta.apache.org/tomcat/examples-taglib

</taglib-uri>

<taglib-location>

/WEB-INF/jsp/example-taglib.tld

</taglib-location>

</taglib>

…

<jsp-property-group>

<description>

Special property group for JSP Configuration JSP example.

</description>

<display-name>JSPConfiguration</display-name>

<url-pattern>/jsp2/misc/config.jsp</url-pattern>

<el-ignored>true</el-ignored>

<page-encoding>ISO-8859-1</page-encoding>

<scripting-invalid>true</scripting-invalid>

<include-prelude>/jsp2/misc/prelude.jspf</include-prelude>

<include-coda>/jsp2/misc/coda.jspf</include-coda>

</jsp-property-group>

</jsp-config>

listener

The listener element specifies the deployment properties for an application listener bean. It has the following subelements:

❑ listener-class : The fully qualified class name of the Java class corresponding to the listener.

❑ description : A text description of the listener.

❑ display-name : A short, descriptive name that can be used by tools while displaying the listener configuration.

❑ icon : The icon element specifies icons that can be used by GUI tools to symbolically represent the listener. It has two subelements: a small-icon and large-icon.

A sample listener element is shown here:

<listener>

<listener-class>listeners.ContextListener</listener-class>

</listener>

<listener>

<listener-class>listeners.SessionListener</listener-class>

</listener>

locale-encoding-mapping-list

This element contains the locale-encoding-mapping element that specifies the mapping between the locale and the encoding. The locale-encoding-mapping element has two child elements:

❑ locale : The locale to be encoded

❑ encoding : The encoding to be used

A sample is shown here:

<locale-encoding-mapping-list>

<locale-encoding-mapping>

<locale>en</locale>

<encoding>en_US</encoding>

</locale-encoding-mapping>

</locale-encoding-mapping-list>

login-config

This element is used to configure the authentication method, the Realm name, and the attributes needed for FORM -based login. It has the following child elements:

❑ auth-method : The authentication method to be used. It must be one of the following: BASIC , DIGEST , FORM , or CLIENT-CERT .

❑ realm-name : The name of the Realm.

❑ form-login-config : If FORM -based authentication is used, this element is used to configure it.

The message-destination element specifies a message destination. The destination specified here is mapped to a physical destination by the deployer. It consists of the following child elements:

❑ message-destination-name : The name of the message destination. This name must be unique across all message destinations described in the deployment descriptor.

❑ description : A text description of the destination.

❑ display-name : A short, descriptive name that can be used by tools while displaying the

destination.

❑ icon : The icon element specifies icons that can be used by GUI tools to symbolically represent the message-destination . It has two subelements: a small-icon and large-icon.

message-destination-ref

The message-destination-ref element declares a reference to a message destination associated with a resource in the deployment component’s environment. It consists of the following child elements:

❑ message-destination-ref-name : Name of the message destination reference. This name is a JNDI name, relative to the java:comp/env context, and must be unique within the deployment descriptor.

❑ message-destination-type : Type of the destination. The type is specified as a fully qualified Java interface that is implemented by the destination.

❑ message-destination-usage : Specifies the use of the message destination. The destination Is used for consuming messages ( Consumes ), producing messages ( Produces ), or both ( Both ).

❑ message-destination-link : Links the message destination reference to a message destination (see the message-destination element described earlier) or a message-driven bean. This value should match the message-destination-name defined in the message-destination element.

❑ description : Used for documentation.

mime-mapping

The mime-mapping element specifies the mapping between the extension for a resource and its MIME type. It has two child elements for this: extension and mime-type . A sample mime-mapping is shown in the following example:

<mime-mapping>

<extension>pdf</extension>

<mime-type>application/pdf</mime-type>

</mime-mapping>

resource-env-ref

This element contains a reference to the administered object associated with a resource. It has the following child elements:

❑ resource-env-ref-name : Name of the resource environment reference. This name is a JNDI name, relative to the java:comp/env context, and must be unique within the deployment descriptor.

❑ resource-env-ref-type : The type of the resource environment reference. This must be the fully qualified name of a Java class or interface.

❑ description : Used for documentation.

resource-ref

The resource-ref element specifies a reference to an external resource. It consists of the following child elements:

❑ res-ref-name : Name of the resource manager connection factory reference. This name is a JNDI name, relative to the java:comp/env context, and must be unique within the deployment descriptor.

❑ res-type : Type of the data source. The type is specified as a fully qualified Java class or interface that is implemented by the data source.

❑ res-auth : Specifies whether the deployment component code signs on programmatically to the resource manager ( Application ), or whether the container signs on to the resource manager on its behalf ( Container ). If the container handles this, the deployer needs to supply information for the sign-on.

The example resource-ref element shown here is a reference to a JDBC DataSource:

<!– JDBC DataSources (java:comp/env/jdbc) –>

<resource-ref>

<description>The default JDBC datasource</description>

<res-ref-name>jdbc/DefaultDS</res-ref-name>

<res-type>javax.sql.DataSource</res-type>

<res-auth>Container</res-auth>

</resource-ref>

security-constraint

This element specifies the security constraints on one or more Web resource collections, as follows:

❑ display-name : The display name for the security constraint.

❑ web-resource-collection : Specifies the resources ( url-pattern element) and the HTTP methods ( http-method element) that are allowed on these resources.

❑ auth-constraint : Indicates the user roles ( role-name element) that are permitted to access the Web resources protected by this security constraint. These role names must match those defined in the security-role element described later in the chapter. The pattern * matches all roles defined in the Web application.

❑ user-data-constraint : Specifies how the data transmitted between the client and the Servlet container is protected. This is done via its transport-guarantee child element, and it can be set to NONE , INTEGRAL , or CONFIDENTIAL .

A sample security-constraint is shown in the following example:

<security-constraint>

<display-name>Example Security Constraint</display-name>

<web-resource-collection>

<web-resource-name>Protected Area</web-resource-name>

<!– Define the context-relative URL(s) to be protected –>

<url-pattern>/security/protected/*</url-pattern>

<!– If you list http methods, only those methods are protected –>

<http-method>DELETE</http-method>

<http-method>GET</http-method>

<http-method>POST</http-method>

<http-method>PUT</http-method>

</web-resource-collection>

<auth-constraint>

<!– Anyone with one of the listed roles may access this area –>

<role-name>tomcat</role-name>

<role-name>role1</role-name>

</auth-constraint>

</security-constraint>

security-role

The security-role element lists all the security roles used in the Web application. These role names are specified via the role-name child element, and are used in the security-constraint to specify the security constraints for a Web application. A sample security-role element is shown in the following example that corresponds to the role used in the securityconstraint in the previous example:

<security-role>

<role-name>role1</role-name>

</security-role>

<security-role>

<role-name>tomcat</role-name>

</security-role>

service-ref

A service-ref element declares a reference to a Web service. It consists of the following child elements:

❑ service-ref-name : The logical name that components in the module use to look up the service. We recommend that this name start with /service/ .

❑ service-interface : The fully qualified class name of the JAX-RPC Service interface on which the client depends.

❑ wsdl-file : The URI location for the WSDL file. The location is relative to the Web application root.

❑ jaxrpc-mapping-file : File that specifies the JAX-RPC mapping between the Java interfaces used by the application and the descriptions in the WSDL file.

❑ service-qname : The name of the WSDL service element.

❑ port-component-reference : This element declares the service endpoint interface or provides the link to a port component that specifies this. It has two child elements:

❑ service-endpoint-interface : A fully qualified Java class that represents the service endpoint interface of a WSDL port

❑ soap-header : Qualified name (qName) of the SOAP header that will be processed by this handler.

❑ soap-role : SOAP actor definitions that the handler will play as a role.

❑ port-name : WSDL port name that the handler is associated with.

❑ description : A text description of the service reference.

❑ display-name : A short, descriptive name that can be used by tools while displaying the service reference.

❑ icon : The icon element specifies icons that can be used by GUI tools to symbolically represent the element. It has two subelements: a small-icon and large-icon (see the icon element, described in more detail earlier in the chapter).

servlet

The servlet element is used to configure a servlet or JSP file. It consists of the following child elements:

❑ servlet-name : The name of the servlet. This must be unique across the Web application.

❑ servlet-class : The fully qualified Java class name of the servlet.

❑ jsp-file : The full path of the JSP file within the Web application (that is, beginning from /). If the load-on-startup element is enabled (described later), then the JSP should be precompiled. Only one of the servlet-class or jsp-file elements should be specified.

❑ init-param : The init-param element is used to pass initialization time parameters to the servlet. This is done via its param-name and param-value elements. It also has a description element that is used to document the parameters.

❑ load-on-startup : The load-on-startup element indicates to the Servlet container that this servlet should be loaded at startup time. This element can also contain an optional positive integer value that specifies the startup sequence. (Lower-integer–valued servlets are loaded before the higher-integer–valued ones.) A negative or missing value indicates that the order doesn’t matter.

❑ run-as : The security role to be used for the execution of the servlet or JSP page. This has two child elements: an optional description and a role-name that specifies the role.

❑ security-role-ref : This element declares the security role reference in a component’s code. It consists of the security role name ( role-name element) and a link to the security role ( rolelink element). It also has an optional description element, again used for documentation purposes.

❑ description : A text description of the listener.

❑ display-name : A short, descriptive name that can be used by tools while displaying the listener configuration.

❑ icon : The icon element specifies icons that can be used by GUI tools to symbolically represent the listener. It has two subelements: a small-icon and large-icon (see the icon element, described in more detail earlier in the chapter).

A sample servlet element is shown here:

<servlet>

<servlet-name>org.apache.jsp.num.numguess_jsp</servlet-name>

<servlet-class>org.apache.jsp.num.numguess_jsp</servlet-class>

</servlet>

servlet-mapping

The servlet-mapping element defines the mapping between a servlet ( servlet-name element) and a URL pattern ( url-pattern element). The servlet-name must match the name defined in the servlet element, as shown in the following example:

<servlet-mapping>

<servlet-name>org.apache.jsp.num.numguess_jsp</servlet-name>

<url-pattern>/num/numguess.jsp</url-pattern>

</servlet-mapping>

New in Servlet 2.5: Wildcards and multiple matching in url-pattern .

Just like filter-mapping , servlet-mapping now allows wildcards and multiple mappings, as shown in this example:

<servlet-mapping>

<servlet-name>color</servlet-name>

<url-pattern>/color/*</url-pattern>

<url-pattern>/colour/*</url-pattern>

</servlet-mapping>

session-config

This element defines the session parameters for the Web application. It has a session-timeout element, which specifies the default session timeout interval, in minutes, for all sessions for this application.

The following example specifies a session timeout of 30 minutes:

<session-config>

<session-timeout>30</session-timeout>

</session-config>

If set to 0 (zero) or less, the session is set to never timeout.

welcome-file-list

This element contains an ordered list of welcome files (for example, index.html ), and is specified via the welcome-file child element. This file is displayed when someone browses to the Web application URL: http://hostname:port/<web application name>/

Following is a sample welcome-file-list element:

<welcome-file-list>

<welcome-file>index.jsp<welcome-file>

<welcome-file>index.html<welcome-file>

<welcome-file>home.html<welcome-file>

</welcome-file-list>

If more than one of these files are present in the Web application, then the order in which they are specified determines which one is shown — the file listed earlier has higher precedence. If none of the files in the example list are found, then, depending on the configuration, an HTTP 404–Not Found error message is displayed.

Configuring Web applications on production and test systems is an important part of an administrator’s job. This involves tasks such as adding or removing filters for given URL patterns, session configuration, error page configuration, the addition of tag libraries, and the configuration of initialization parameters for the Web application. Understanding the Web application structure and the deployment descriptor is, therefore, important for administrators