Servlet for serving static content
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:
If-Modified-Since
header (ie custom getLastModified
method) 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).
I came up with a slightly different solution. It's a bit hack-ish, but here is the mapping:
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>myAppServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
This basically just maps all content files by extension to the default servlet, and everything else to "myAppServlet".
It works in both Jetty and Tomcat.
在这种情况下,不需要完全自定义实现默认的servlet,您可以使用这个简单的servlet将请求包装到容器的实现中:
package com.example;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DefaultWrapperServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
RequestDispatcher rd = getServletContext().getNamedDispatcher("default");
HttpServletRequest wrapped = new HttpServletRequestWrapper(req) {
public String getServletPath() { return ""; }
};
rd.forward(wrapped, resp);
}
}
我使用FileServlet获得了很好的结果,因为它支持几乎所有的HTTP(etags,chunking等)。
链接地址: http://www.djcxy.com/p/46220.html上一篇: 通过xmlHttpRequest将文件作为multipart发送
下一篇: 用于提供静态内容的Servlet