Wednesday, October 11, 2006

Configuring Tomcat to serve static files

For a long time now, I have been trying to figure out how to specify a default servlet in Tomcat 5 and still allows for static files to be served.

From all of my readings, I have noticed that in order to have a default servlet and serve static files, I would have to serve the files via my servlet. I didn't like this solution. Finally, I have discovered a work around...

To outline the problem, imagine that your web.xml file contains the following:

<servlet-mapping>
<servlet-name>My Servlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

Now all requests to your webapp are going to go through 'My Servlet'. So if you ask for a file like http://localhost:8080/your_app/myStyleSheet.css, Tomcat will look at the request and forward it to 'My Servlet'.

Now unless that particular servlet contains code to handle the case for myStyleSheet.css, nothing will happen (depends on your 'My Servlet' code of course; 404 might be returned, etc).

So one work around that I have found is to enter the following in your tomcat/webapps/your_app/WEB-INF/web.xml:

<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>

With that code all requests for a file ending in the prefix css will not be sent to 'My Servlet'. Instead Tomcat will look for the file in your web apps home directory and if found, serve it, otherwise a 404 is returned.

Now that I have found this one solution, it seems to me like it was obvious (maybe that's why I couldn't find it in all my web searching with google) ...