如何在 AbstractAnnotationConfigDispatcherServletInitializer Spring 中进行过滤器映射 [英] How to do filter mapping in AbstractAnnotationConfigDispatcherServletInitializer Spring
问题描述
问题是:我可以成功注册过滤器,但不知道如何使用此特定配置设置映射 URL.
Here is the problem: I can successfully register the Filter, but don't know how to set the mapping URL using this specific configuration.
这是我的班级:
public class WebInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{AppConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebConfig.class};
}
@Override
protected Filter[] getServletFilters() {
return new Filter[]{
new DelegatingFilterProxy("springSecurityFilterChain"),
new DelegatingFilterProxy("customFilter")
};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
PD我已经使用 WebApplicationInitializer
完成了它,但我想使用 AbstractAnnotationConfigDispatcherServletInitializer
.
P.D.
I had done it using WebApplicationInitializer
, but I want to use AbstractAnnotationConfigDispatcherServletInitializer
.
推荐答案
我能够做到这一点的唯一方法是使用 FilterRegistration.Dynamic 接口.在您的 WebInitializer 类中,在 onStartup 方法(来自超类的覆盖)中手动添加您的自定义过滤器.据我所知,目前没有比这更优雅的方法了.
The only way I was able to do this was to use the FilterRegistration.Dynamic interface. In your WebInitializer class, add your custom filter manually in the onStartup method (an override from a superclass). There is no way that is more elegant at the moment to my knowledge.
@Override
public void onStartup(ServletContext servletContext)
throws ServletException {
FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("my-filter", new MyFilter());
encodingFilter.setInitParameter("blah", "blah");
encodingFilter.addMappingForUrlPatterns(null, false, "/toBeFiltered/*");
super.onStartup(servletContext);
}
如果您希望此过滤器正常工作,那么最好将您已覆盖的 getServletFilters 方法注释掉,以便从 servletContext 正确返回此过滤器.
If you want this filter to work correctly then it would be best for you to comment out the getServletFilters method you have overridden so that this filter is served back correctly from the servletContext.
这篇关于如何在 AbstractAnnotationConfigDispatcherServletInitializer Spring 中进行过滤器映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!