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

一个人想着一个人 提交于 2019-12-13 06:49:38

问题


I am converting a web.xml file to Java based configuration using Spring-web's WebApplicationInitializer. Following is the sample filter defined

<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>

and now the WebApplicationInitializer class looks like this

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

But as you can see, the Filter is applied to all the resources, whereas I want to map the Filter just for /sampleUrl. How do we do that?


回答1:


Below a full example i used in one of my project :

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


来源:https://stackoverflow.com/questions/35434978/how-to-specify-url-pattern-for-servlet-filters-in-webapplicationinitializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!