ProblemYou want to link a URL pattern that looks like a JSP file request to a servlet. SolutionCreate a servlet-mapping element that includes a JSP-style URL pattern. DiscussionI mentioned in the previous recipes that you have a lot of latitude when creating aliases that point to servlets. For instance, a request that appears to access a JSP file can easily be mapped to a servlet. The deployment descriptor in Example 3-4 maps the URL pattern / info .jsp to the JspInfo servlet. Example 3-4. Deployment descriptor example of mapping a JSP-style URL to a servlet<?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>JspInfo</servlet-name> <servlet-class>com.parkerriver.cookbook.JspInfo</servlet-class> </servlet> <servlet-mapping> <servlet-name>JspInfo</servlet-name> <url-pattern>/info.jsp</url-pattern> </servlet-mapping> </web-app> The forward slash that begins the URL pattern /info.jsp means "begin at the root of the web application that uses this deployment descriptor." So the entire URL for the JspInfo servlet looks like this for the cookbook web application: http://www.mysite.org/cookbook/info.jsp . You can also map all references to JSP pages to a single servlet, as shown in Example 3-5, which uses a web.xml entry with an extension mapping. Example 3-5. Mapping all JSP URLs to a single servlet<?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>JspInfo</servlet-name> <servlet-class>com.parkerriver.cookbook.JspInfo</servlet-class> </servlet> <servlet-mapping> <servlet-name>JspInfo</servlet-name> <url-pattern>*.jsp</url-pattern> </servlet-mapping> </web-app> Make sure to exclude the slash ( / ) in the URL pattern, as an extension mapping that uses a file extension suffix begins with an asterisk and ends with a period and the suffix itself, as in <url-pattern>*.jsp</url-pattern> . This type of mapping may be useful if you were migrating an application from one version that used a lot of JSP pages to a new version that relied entirely on servlets. This takes care of users who have bookmarked many URLs that involve JSP files.
See AlsoChapter 1 on web.xml ; Recipe 3.1 and Recipe 3.2; Recipe 3.4-Recipe 3.8; Chapter 11 of the Servlet v2.3 and 2.4 specifications on mapping requests to servlets. |