Java web applications use a deployment descriptor file to determine how URLs map to servlets, which URLs require authentication, and other information. This file is named web.xml
, and resides in the app's WAR under the WEB-INF/
directory. web.xml
is part of the servlet standard for web applications
The deployment descriptor is a file named web.xml
. It resides in the app's WAR under the WEB-INF/
directory. The file is an XML file whose root element is <web-app>
.
Here is a simple web.xml
example that maps all URL paths (/*
) to the servlet class mysite.server.ComingSoonServlet
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>comingsoon</servlet-name>
<servlet-class>mysite.server.ComingSoonServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>comingsoon</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
To map a URL to a servlet, you declare the servlet with the <servlet>
element, then define a mapping from a URL path to a servlet declaration with the <servlet-mapping>
element
<servlet>
<servlet-name>redteam</servlet-name>
<servlet-class>mysite.server.TeamServlet</servlet-class>
<init-param>
<param-name>teamColor</param-name>
<param-value>red</param-value>
</init-param>
<init-param>
<param-name>bgColor</param-name>
<param-value>#CC0000</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>blueteam</servlet-name>
<servlet-class>mysite.server.TeamServlet</servlet-class>
<init-param>
<param-name>teamColor</param-name>
<param-value>blue</param-value>
</init-param>
<init-param>
<param-name>bgColor</param-name>
<param-value>#0000CC</param-value>
</init-param>
</servlet>
The <servlet-mapping>
element specifies a URL pattern and the name of a declared servlet to use for requests whose URL matches the pattern.
<servlet-mapping>
<servlet-name>redteam</servlet-name>
<url-pattern>/red/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>blueteam</servlet-name>
<url-pattern>/blue/*</url-pattern>
</servlet-mapping>
With this example, a request for the URL http://www.example.com/blue/teamProfile
is handled by the TeamServlet
class, with the teamColor
parameter equal to blue
and the bgColor
parameter equal to #0000CC
.