WebApplicationInitializer

WebApplicationInitializer

我正在使用Spring-web的web.xmlWebApplicationInitializer文件转换为基于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 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));
}

10-08 13:27