Servlet for serving static content

jakarta-ee, java, jsp, servlets

Solution

I ended up rolling my own `StaticServlet`. It supports `If-Modified-Since`, gzip encoding and it should be able to serve static files from war-files as well. It is not very difficult code, but it is not entirely trivial either.

The code is available: StaticServlet.java. Feel free to comment.

Update: Khurram asks about the `ServletUtils` class which is referenced in `StaticServlet`. It is simply a class with auxiliary methods that I used for my project. The only method you need is `coalesce` (which is identical to the SQL function `COALESCE`). This is the code:

public static <T> T coalesce(T...ts) {
    for(T t: ts)
        if(t != null)
            return t;
    return null;
}

Problem

I deploy a webapp on two different containers (Tomcat and Jetty), but their default servlets for serving the static content have a different way of handling the URL structure I want to use (details). I am therefore looking to include a small servlet in the webapp to serve its own static content (images, CSS, etc.). The servlet should have the following properties: - No external dependencies - Simple and reliable - Support for `If-Modified-Since` header (i.e. custom `getLastModified` method) - (Optional) support for gzip encoding, etags,... Is such a servlet available somewhere? The closest I can find is example 4-10 from the servlet book. Update: The URL structure I want to use - in case you are wondering - is simply: ``` <servlet-mapping> <servlet-name>main</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/static/*</url-pattern> </servlet-mapping> ``` So all requests should be passed to the main servlet, unless they are for the `static` path. The problem is that Tomcat's default servlet does not take the ServletPath into account (so it looks for the static files in the main folder), while Jetty does (so it looks in the `static` folder).

Original source

Related problems