2 Minutes To Code (β Version)

Apache Tomcat - 2 minute tutorial

How to configure servlets using deployment descriptor (web.xml)

A web-app needs a deployment descriptior or DD (the web.xml file located inside the war file's WEB_INF folder) to map the urls that the http clients hit with the corresponding servelt/jsp that will handle that http request. Apart from this, the DD also contains such configurations as welcome file list, filters, listeners, seesion timeout etc.

Let's see how to configure servlets and the corersponding url mapping in DD.

To configure a servlet, you need a <servlet> element and a <servlet-mapping> element as shown in the first xml below. The servlet element contains a <servlet-class> which is the fully qualfied name of the java servlet class and the servlet-mapping element contains a <url-pattern> element which is the url that client hits. The <servlet-name> element in both these elements just links servlet element with servlet-mapping element. With this configuration whenever, a client hits http://ip:port/appname/main/welcome.do, tomcat will pass the request to servlet class com.techfundaes.servlets.Welcome.java for processing.
<web-app>
   
   <servlet>
      <servlet-name>welcomePage</servlet-name>
      <servlet-class>com.techfundaes.servlets.Welcome</servlet-class>
   </servlet>

   <servlet-mapping>
      <servlet-name>welcomePage</servlet-name>
      <url-pattern>/main/welcome.do</url-pattern>
   </servlet-mapping>

</web-app>

If you specify the url-pattern as * (asterisk) as in the xml below, then all urls received by the web-app will be processed by the configured welComePage servlet.
 
<servlet-mapping>
          <servlet-name>welcomePage</servlet-name>
          <url-pattern>*</url-pattern>
       </servlet-mapping>

If you specify the url-pattern as /sectionA/* (asterisk) as in the xml below, then all urls which point to any resource under sectionA will be served by configured welcomePage servlet.
<servlet-mapping>
      <servlet-name>welcomePage</servlet-name>
      <url-pattern>/sectionA/*</url-pattern>
   </servlet-mapping>

If you wan to serve all urls ending with a given extension (eg. .jsp ), then use the servlet-mapping as shown below.
<servlet-mapping>
      <servlet-name>welcomePage</servlet-name>
      <url-pattern>*.jsp</url-pattern>
   </servlet-mapping>