Recipe 3.4 Mapping Static Content to a Servlet


Problem

You want requests for static content such as HTML-style URLs to request a servlet.

Solution

Use a servlet-mapping element in web.xml to map the servlet name to the static content.

Discussion

It 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 .

Make sure that URL patterns never begin with a slash ( / ) when you are creating extension mappings.


See Also

Chapter 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.



Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net