0

我正在web.xml使用 Spring-web 将文件转换为基于 Java 的配置WebApplicationInitializer。以下是定义的示例过滤器

<filter>
        <filter-name>sampleFilter</filter-name>
        <filter-class>com.SampleFilter</filter-class>
</filter>
<filter-mapping>
        <filter-name>sampleFilter</filter-name>
        <url-pattern>/sampleUrl</url-pattern>
</filter-mapping>

现在 WebApplicationInitializer 类看起来像这样

class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
   @Override
  protected Filter[] getServletFilters() {
    return new Filter[]{new SampleFilter()};
  }
  //other methods
} 

但正如您所看到的,过滤器适用于所有资源,而我只想将过滤器映射为/sampleUrl. 我们如何做到这一点?

4

1 回答 1

5

下面是我在一个项目中使用的完整示例:

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();

    //add MVC dispatcher servlet and map it to /
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
    dispatcher.setAsyncSupported(true);

    //add spring characterEncoding filter
    //to always have encoding on all requests
    EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ERROR);

    CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
    characterEncodingFilter.setEncoding("UTF-8");
    characterEncodingFilter.setForceEncoding(true);

    FilterRegistration.Dynamic characterEncoding = servletContext.addFilter("characterEncoding", characterEncodingFilter);
    characterEncoding.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
    characterEncoding.setAsyncSupported(true);

    // specifies that the parser produced by this factory will
    // validate documents as they are parsed.
    SAXParserFactory.newInstance().setValidating(false);

    // add spring contextloader listener
    servletContext.addListener(new ContextLoaderListener(rootContext));
}
于 2016-02-16T14:25:53.770 回答