[ Team LiB ] Previous Section Next Section

Recipe 3.4 Mapping Static Content to a Servlet


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


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


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"


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:


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.

    [ Team LiB ] Previous Section Next Section