要配一个default servlet, 以免静态资源被其他servlet处理; 还要再配一个default filter,以免静态资源被其他filter处理
<filter> <filter-name>defaultFilter</filter-name> <filter-class>somepackage.DefaultFilter</filter-class> </filter> <filter-mapping> <filter-name>defaultFilter</filter-name> <url-pattern>favicon.ico</url-pattern> <url-pattern>/js/*</url-pattern> </filter-mapping> <!--其他filter mapping--> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>favicon.ico</url-pattern> <url-pattern>/js/*</url-pattern> </servlet-mapping> <!--......--> <servlet-mapping> <servlet-name>mvcDispatch</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
public class DefaultFilter implements Filter { private RequestDispatcher defaultRequestDispatcher; @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { defaultRequestDispatcher.forward(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { this.defaultRequestDispatcher = filterConfig.getServletContext() .getNamedDispatcher("default"); } }
default servlet则不用写,因为主流容器都自带了这个servlet. 注意default servlet并不是servlet官方规范承认的一个servlet, 所以这种做法会有可移植性隐患。只不过,主流容器都有这个servlet并且都命名为default,所以只要你不用什么特别的容器,就不会有问题。