Thursday, September 9, 2010

The Deployment Descriptor (web.xml)

The web.xml file provides configuration and deployment information for the web components that comprise a web application. Examples of web components are servlet parameters, servlet and JavaServer Pages (JSP) definitions, and Uniform Resource Locators (URL) mappings. The Java Servlet specification defines the web.xml deployment descriptor file in terms of an XML schema document. 

Listing 1 contains the source for a default web.xml file.


Listing 1 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/j2ee/dtds/web-app_2_3.dtd">

<web-app>
</web-app>

You may also see versions of the deployment descriptor that uses what is called a schema which is functionally equivalent. The start of a deployment descriptor that uses a schema will look as follows

<?xml version="1.0" encoding="UTF-7"?>
<web-app version="3.0"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmnls:xsi="http://www.w3.org/2001/XML-Schema -instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
               http://java.sun.com/xml/ns/javae/web-app_3_0.xsd">
</web-app>



The web-app element is the root of the deployment descriptor for a web application. Note that the sub elements of this element can be in arbitrary order

web.xml Deployment Descriptor Elements

The following sections describe the deployment descriptor elements defined in the web.xml file under the root element <web-app>:

  • context-param         
                The optional context-param element contains the declaration of a web application's servlet context initialization parameters.

  • servlet
       The servlet element contains the declarative data of a servlet. The servlet tag has two mandatory sub tags, <servlet-name> and <servlet-class>. The servlet-class tag is the fully qualified name of the class that is to be executed and the servlet-name tag is an alias for use elsewhere within the deployment descriptor. 

    <servlet>
        <servlet-name>
HelloWorldServlet</servlet-name>
        <servlet-class>com.servlet.HelloWorld</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

The load-on-startup tag of the servlet indicates that the servlet should be loaded (instantiated and have its init() called) on the startup of the web application. The optional contents of these element must be an integer indicating the order in which the servlet should be loaded. 
  • If the value is a negative integer, or the  element is not present, the container is free to load the servlet whenever it  chooses.
  • If the value is a positive integer or 0, the container must load and  initialize the servlet as the application is deployed.   

The container must guarantee that servlets marked with lower integers are loaded before servlets marked with higher integers. The container may choose the order of loading of servlets with the same load-on-start-up value. 

The servlet element may also have the following optional sub-elements display-name,description,init-param, run-as, security-role-ref

  • servlet-mapping
      The servlet-mapping element defines a mapping between a servlet and a URL pattern. Without a servlet-mapping a servlet cannot be retrieved by a visiting browser. The following example shows a servlet mapped to a url pattern.

    <servlet-mapping>
        <servlet-name>HelloWorldServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

servlet-name tag contains the name of the servlet to which you are mapping a URL pattern. This name corresponds to the name you assigned a servlet in a <servlet> declaration tag.

url-pattern describes a pattern used to resolve URLs. The portion of the URL after the http://host:port + WebAppName is compared to the <url-pattern>. If the patterns match, the servlet mapped in this element will be called.

Given this mapping the servlet contained within the Java file at com.servlet.HelloWorld will be executed when a browser requests http://localhost/hello. The url-pattern tag can include wildcards and it is possible to have multiple mappings to a single servlet.

The url-mapping value must begin with a forward slash unless it is an extension mapping. By extension mapping I mean where a wildcard is used, e.g. to map the URL pattern *.exam to a servlet you could include the value
<url-pattern>*.exam</url-pattern>. 

But apart from that, mappings begin with a forward slash.

  • welcome-file-list
       The optional welcome-file-list element contains an ordered list of welcome-file elements. The welcome-file tag can be used to mark a servlet or a JSP file as the default first page that is returned when a visitor accesses a URL if they don't specify an explicit file. This is typically used on the home page of a web site where you see the trailing slash of the URL but you don't see the name of the file that is actually returned.

    <welcome-file-list>
        <welcome-file>welcomeservlet</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
The idea of allowing multiple welcome files might seem odd at first, after all, only one file can be returned if there is no explicit file name given. The idea of allowing multiple files is that you might have a directory structure that contains files you want to use as the default welcome file. A welcome-file value cannot start or end with a slash, and they will be picked in the order they appear in the deployment descriptor. Thus given a deployment descriptor with the following tags.
     <welcome-file-list>
  <welcome-file> index.jsp </welcome-file>  
        <welcome-file> welcome.jsp </welcome-file>
     </welcome-file-list>

The index.jsp file will be returned from a request to www.mydomain.com/. If no index.jsp file exists then welcome.jsp will be returned if it exists.

  • error-page
      The optional error-page element specifies a mapping between an error code or exception type to the path of a resource in the Web application. When an error occurs—while server is responding to an HTTP request, or as a result of a Java exception— server returns an HTML page that displays either the HTTP error code or a page containing the Java error message. You can define your own HTML page to be displayed in place of these default error pages or in response to a Java exception.

 Thus the following tags would re-direct all SQL exception errors to the /errorpage.jsp page.
    <error-page>
       <exception-type> java.sql.SQLException </exception-type>
       <location> /errorpage.jsp </location>
    </error-page> 

The following tags would re-direct all HTTP 404 errors to the /errorpage.jsp page
   <error-page>
      <error-code>404</error-code>
      <location>/errorpage.jsp</location>
   </error-page>
Note that it is possible to define a specific error page for an individual JSP page using the errorPage attribute as follows.
    <%@ page errorPage="MyErrorPage.jsp" %>
The page that this attribute points to must have the isErrorPage=true attribute set as follows.
   <%@ page isErrorPage="true" %>
  • init-param
This is an element within the servlet. The optional init-param element contains a name/value pair as an initialization attribute of the servlet. Use a separate set of init-param tags for each attribute.

The init-param tag allows initialisation parameters to be passed to a servlet via the deployment descriptor. This allows configuration without having to recompile code. 

An example of how you might use the init-param tag is to inform a servlet of the JDBC driver, and username and password to access a database.The following extract from a deployment descriptor shows how the init-param called backupfrequency could be used to inform a servlet of the interval between backups. 
    <servlet>
        <servlet-name>backupservlet</servlet-name>
        <servlet-class>com.servlet.BackupServlet</servlet-class>
        <init-param> 
            <description>Frequency of backup in hours</description>
            <param-name>backupfrequency</param-name>
            <param-value>24</param-value>
        </init-param>
    </servlet> 
The servlet can retrieve the value of the init-param through code similar to the following.
    ServletConfig config = getServletConfig();
   backupfrequency = config.getInitParameter("backupfrequency");
 

1 comment:

  1. Its very nce to read .Thanks a lot! You made a new blog entry to answer my question; I really appreciate your time and effort.
    java training in chennai

    ReplyDelete