ProblemYou want to create several names or URL patterns that web users can use to request a single servlet. SolutionAssociate the servlet element with more than one servlet-mapping element in the deployment descriptor. DiscussionYou can create a number of servlet-mapping elements for a single servlet, as shown in Example 3-2. A user can access this servlet by using one of two addresses: http://www.mysite.org/cookbook/cookieservlet or http://www.mysite.org/cookbook/mycookie . Example 3-2. Two servlet-mapping tags<?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/dtd/web-application_2_3.dtd" > <web-app> <servlet> <servlet-name>CookieServlet</servlet-name> <servlet-class>com.parkerriver.cookbook.CookieServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CookieServlet</servlet-name> <url-pattern>/cookieservlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>CookieServlet</servlet-name> <url-pattern>/mycookie</url-pattern> </servlet-mapping> </web-app> Remember that the servlet-mapping elements have to appear after all of the servlet elements in the servlet 2.3 deployment descriptor.
You can use a wildcard character ( * ) to extend your mapping pattern. The mappings in Example 3-3 invoke the CookieServlet for all of the URLs that begin with /cookie/ , and then optionally include any names after the forward slash. For example, CookieServlet can be invoked with a URL of http://www.mysite.org/cookbook/cookie/you using this descriptor. This is because the url-pattern matches any HTTP requests ending with the "/cookie/" string. Example 3-3. Using an asterisk in the URL pattern<?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/dtd/web-application_2_3.dtd" > <servlet> <servlet-name>CookieServlet</servlet-name> <servlet-class>com.jspservletcookbook.CookieServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CookieServlet</servlet-name> <url-pattern>/cookie/*</url-pattern> </servlet-mapping>
See AlsoChapter 1 on web.xml; Recipe 3.1; Recipe 3.3-Recipe 3.8; Chapter 11 of the Servlet v2.3 and 2.4 specifications on mapping requests to servlets. |