The web deployment descriptor

The web deployment descriptor XML file is the traditional method for Java web developers to configure Servlets, filters, and listeners in a Java EE application. The file must be named web.xml, and the specification mandates that it will be found in the WAR file under the folder WEB-INF/.

The web deployment descriptor describes the Servlet classes, filters, and listeners, the environment and resources, and other configurations of a web application. Putting the information all together, inform the web container how to serve the content from the incoming web requests.

The simplest possible deployment descriptor for Servlet 3.1 and beyond looks just like the following code:

<?xml version = "1.0" encoding = "ISO-8859-1"?>
<web-app xmlns = "http://java.sun.com/xml/ns/javaee"xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation = "http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"version = "3.1">
</web-app>

XML has a well-defined schema definition that can be found on Oracle's public website at http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd. The root XML element must be <web-app>.

Mapping Java Servlets

An expanded deployment descriptor maps the annotated Servlets from earlier, SimpleServlet and SimpleServletWithInitParams, into the equivalent XML file as follows:

<?xml version = "1.0" encoding = "UTF-8"?>
<web-app xmlns = "http://java.sun.com/xml/ns/javaee"xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation = "http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"version = "3.1">
<display-name>A Simple Application</display-name>
  <servlet>
    <servlet-name>simple</servlet-name>
      <servlet-class>
        je7hb.servlets.simple.SimpleServlet
      </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>simple</servlet-name>
      <url-pattern>/simple</url-pattern>
    </servlet-mapping>

  <servlet>
    <servlet-name>initparams</servlet-name>
      <servlet-class>
        je7hb.servlets.simple.SimpleServletWithInitParams
      </servlet-class>
      <init-param>
        <param-name>source</param-name>
        <param-value>Liverpool Central</param-value>
      </init-param>
      <init-param>
        <param-name>target</param-name>
        <param-value>London Euston</param-value>
      </init-param>
      <init-param>
        <param-name>time</param-name>
        <param-value>17:45:00</param-value>
      </init-param>
        <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>initparams</servlet-name>
    <url-pattern>/initparams</url-pattern>
  </servlet-mapping>
</web-app>

The first thing to notice is the greater verbosity of the XML configuration compared to the annotations on the Servlet classes. On the other hand, auto-completion XML is an essential feature of all of the best IDEs nowadays. The root element of this XML document is <web-app>. According to the Servlet specification, the subelements can be arranged in an arbitrary order. Hence, for better readability, we arranged the grouping of the <servlet> element next to the corresponding mapping element <servlet-mapping>.

The <servlet> element defines a Java Servlet with the name and the fully qualified class name. The tag allows multiple instances of the Servlet class to be used, but mapped by different class names. The name for each Servlet is unique across the deployment descriptor. The <servlet> element can also optionally accept the initialization parameters.

The <servlet-mapping> elements configure how the web container maps a Servlet or associates it with an incoming web request. It takes Servlet and at least one URL pattern.

The <load-on-startup> element allows developers to configure the initialization order for Servlets. The configuration is an integer value starting from zero; the lower the number, the higher the priority. It comes in useful when your application has a Servlet that must be started before an other Servlet. A reasonable situation is initializing a database connection, reading data from static files, or setting up a cache of application-wide constant values.

Two servlets mapping can share a Servlet class. An example of a Servlet for a retail superstore business model that has two operational divisions, namely home and garden, and food store market, is as follows:

<servlet>
  <servlet-name>homegarden</servlet-name>
    <servlet-class>superstore.ProductListing</servlet-class>
    <init-param>
      <param-name>operations</param-name>
      <param-value>home_and_garden</param-value>
    </init-param>
</servlet>

<servlet>
  <servlet-name>foodstore</servlet-name>
    <servlet-class>superstore.ProductListing</servlet-class>
    <init-param>
      <param-name>operations</param-name>
      <param-value>food_store</param-value>
    </init-param>
</servlet>

<servlet-mapping>
  <servlet-name>homegarden</servlet-name>
    <url-pattern>/garden/*</url-pattern>
</servlet-mapping>

<servlet-mapping>
  <servlet-name>foodstore</servlet-name>
    <url-pattern>/food/*</url-pattern>
</servlet-mapping>

The ProductListing Servlet is shared between two URL patterns, because the Servlet class is given two different names homegarden and foodstore. The Servlet names are then mapped to separate URL patterns.

A URL pattern can begin with the wildcard character (*), in which case it is really an extension, or it is placed at the end of the string after a forward slash character (/).

Suppose there is a fictional website named www.hype7.co.uk and assume there is an appropriate URL rewriting going on behind the scene, then the food items are accessible through an example, such as http://www.hype7.co.uk/food/fish/seabass/recipe/101. The same processing takes for the gardening section of the e-commerce store: http://www.hype7.co.uk/garden/sheds/wooden/list.

Execution of the code inside Servlet can distinguish between the operations by inspecting the Servlet initialization parameters. You have already seen how to do this.

Configuring a session timeout

Web container provides a javax.servlet.http.HttpSession object instance for each unique web client that connects to the web application. HttpSession is designed for saving and retrieving the content that survives from the Servlet request. The session can be approximated to the user's session, it does not maintain the conversational state, however.

The configurator can control how long HttpSession will stay alive for a web client through web.xml.

The developer can configure how long HttpSession will stay alive for an idle web client through web.xml. Inside the deployment descriptor, the <session-config> element is a child <web-app> element, we can set the value of the idle time of 10 minutes as follows:

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

<session-config> is a subelement of the web-app root element. The <session-timeout> element specifies the time in minutes.

Configuring MIME types

In order to support Multipurpose Internet Mail Extensions (MIME) types in the web application, developers can specify the types and their association file suffixes. Web container uses a mapping of suffixes to MIME type when it is asked to serve the static content. The mapping is defined by the <mime-mapping> element, which has two subelements, namely <extension> and <mime-type>, in order respectively.

An example of these MIME settings is as follows:

<mime-mapping>
  <extension>csv</extension>
    <mime-type>application/csv</mime-type>
</mime-mapping>
<mime-mapping>
  <extension>pdf</extension>
    <mime-type>application/pdf</mime-type>
</mime-mapping>

The <mime-mapping> element is a direct child of the <web-app> root document element.

Given a fictional two URLs that represent a static resource URL, if the preceding MIME mapping is applied in the web application, then http://localhost:8080/mywebapp/datasheet/whitepaper.csv and http://localhost:8080/mywebapp/datasheet/whitepaper.pdf serve as the comma-separated value and the PDF files respectively.

Dynamic resources such as a Servlet, JSP, or JSF must set their respective content type by calling the ServletResponse.setContentType() method with the standard MIME type string accordingly.

Configuring the welcome page

A web application can configure its own welcome page, which serves as the default, when the URL is just referenced by the directory. By default, the welcome page is index.jsp and then index.html. The welcome pages are useful when the web request is referencing just the path and not a resource. They specify the files that the containers are searching in the path directory in order to serve the client. The element <welcome-file-list> is a child of <web-app>, and configures these settings.

An example of the configuration in the web deployment descriptor is as follows:

<welcome-file-list>
  <welcome-file>index.xhtml</welcome-file>
  <welcome-file>index.jsp</welcome-file>
  <welcome-file>index.html</welcome-file>
</welcome-file-list>

Web container will search for index.jsp; if it is there on the path, the container serves it. Otherwise, the container looks for the next file on the list, and it then attempts to find the static resource index.html in order to serve that.

Configuring the error-handler pages

The container can only configure to serve error pages if a Java Servlet generates an error code in order to signify an abnormal request. The web deployment descriptor allows developers to direct HTTP errors to a specific page, which is useful for providing an application error page.

The <error-page> element configures error handling for a specific HTTP error code, such as 404, the resource does not exist, or 500, the resource is forbidden from access. This element is a child of the <web-app> element and it has two children. The <error-code> tag specifies the HTTP error code and the <location> tag specifies a resource to serve as the error-handling page, which can be a dynamic resource.

An example of the error-handling XML is as follows:

<error-page>
  <error-code>404</error-code>
  <location>/errors/404.html</location>
</error-page>

In the previous example, the XML maps the HTTP Error 404 to the specific error page as a static HTML file.

In order to send an error in a Servlet, you can invoke the method sendError() on the HttpServletResponse object as the following code demonstrates:

resp.sendError(HttpServletResponse.SC_NOT_FOUND);

SC_NOT_FOUND is a static constant, which is final and a primitive integer with the value of 404.

Annotations and the web deployment descriptor

Annotations and the web deployment descriptor can be freely mixed. Developer has control of whether the configuration in WEB-INF/web.xml overrides the annotations. Web container will ignore Servlet 3.0 and better annotations on any defined classes, if the <web-app/> element is supplied with an attribute metadata-complete, and is set to true.

A web container with a deployment descriptor is as follows:

<?xml version = "1.0" encoding = "ISO-8859-1"?>
<web-app xmlns = "http://java.sun.com/xml/ns/javaee"xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation = "http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"version = "3.0" metadata-complete = "true">
<!-- . . . -->
</web-app>

Applying metadata-complete = "true" causes the Servlet container to ignore the annotations on any Java Servlets, filters, and listeners. Setting metadata-complete to true, effectively says that the web deployment descriptor is the configuration, and replicates the behavior of the Servlet web container before Version 3.0.

The order of priority for a web container is to load and process the annotations, if they are present. Web container will search for the annotations in two locations: compiled classes under the folder /WEB-INF/classes and also the libraries in JARs under /WEB-INF/lib. It will apply the configuration to create internal metadata. Only afterwards will web container examine /WEB-INF/web.xml for the metadata configuration. The reason for this behavior is that there may not be any web deployment descriptor available, as you have already seen in the first Servlet example.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.31.165