如何在 WebApplicationInitializer 中为 Servlet 过滤器指定 url-pattern?

How to specify url-pattern for Servlet filters in WebApplicationInitializer?

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

<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 看起来像这样

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

但是如您所见,过滤器应用于所有资源,而我只想为 /sampleUrl 映射过滤器。我们该怎么做?

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

@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));
}