How do I map requests to my application name to a servlet?
Author: Deron Eriksson
Description: This Java servlet tutorial describes how to map an application name to a servlet using a welcome-file.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1 || Tomcat 5.5.20


Page:    1 2 >

When a browser hits your application using just the application name (for example, "http://localhost:8080/tomcat-demo"), it's possible to send that request to a destination such as an HTMLW file, a JSPW, or a servletW using the <welcome-file-list> and <welcome-file> elements in web.xmlW. The tutorial consists of one servlet and a web.xml file and will demonstrate using a servlet as a <welcome-file>. The project structure is shown below.

'tomcat-demo' project

The web.xml file has one servlet called TestServlet. The URL pattern /test maps to the TestServlet, so if you hit "http://localhost:8080/tomcat-demo/test", this would get directed to TestServlet.

Notice that the web.xml file contains the <welcome-file-list> and <welcome-file> elements. The welcome-file-list specifies 1 or more potential welcome-files. If a request is made to just the application name, this request gets directed to the resources in the welcome-file-list. If the first resource doesn't exist, the next resource will be used, and so forth until a valid resource is found. If a valid resource is found, all welcome-files after the valid resource are ignored.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="tomcat-demo" version="2.4"
	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_4.xsd">
	<servlet>
		<servlet-name>TestServlet</servlet-name>
		<servlet-class>test.TestServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>TestServlet</servlet-name>
		<url-pattern>/test</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>test</welcome-file>
		<welcome-file>this-is-not-reached-since-test-exists.jsp</welcome-file>
	</welcome-file-list>
</web-app>

Since the 'test' resouce is a valid resource ('/test' is specified to map to TestServlet), requests to the application name will be sent to TestServlet.

(Continued on page 2)

Page:    1 2 >