| [ Team LiB ] |
|
Recipe 3.4 Mapping Static Content to a ServletProblemYou want requests for static content such as HTML-style URLs to request a servlet. SolutionUse a servlet-mapping element in web.xml to map the servlet name to the static content. DiscussionIt often seems odd to the casual programmer, but you can have a servlet respond to a URL that appears to be static content, such as an HTML file. Example 3-6 maps the servlet HtmlServlet to all URLs ending in the .html suffix. Any request within the web application that contains this deployment descriptor and specifies a file ending with .html is directed to HtmlServlet. Example 3-6. Mapping static content to a servlet in web.xml<?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>HtmlServlet</servlet-name>
<servlet-class>com.jspservletcookbook.HtmlServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HtmlServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
The servlet-mapping element in this listing contains an extension-mapping URL pattern: it begins with an asterisk and ends with .html. If you want to map the servlet to just one HTML file, use XML that looks like this: <url-pattern>myfile.html</url-pattern>. Using this pattern, only requests for the myfile.html file are directed to HtmlServlet.
See AlsoChapter 1 on web.xml; Recipe 3.3; Recipe 3.5-Recipe 3.8; Chapter 11 of the Servlet v2.3 and 2.4 specifications on mapping requests to servlets. |
| [ Team LiB ] |
|