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