如何在Spring中使用WebMvcConfigurerAdapter添加过滤器?
如何在Spring中使用WebMvcConfigurerAdapter添加过滤器?
使用 WebApplicationInitializer
,我可以在 onStartup()
方法中轻松地向 ServletContext
添加过滤器。
如何使用 WebMvcConfigurerAdapter
添加过滤器?我必须使用 XML 吗?
ADD 1
为了帮助其他人更轻松地理解 Spring Web 配置,我绘制了以下插图。
现在你只需要先了解 Spring Web 配置背后的 理性
。然后从下面挑选要继承的配置类和要覆盖的方法。
查找比记忆这么多事情更不痛苦。
还有一篇关于 Spring Web 初始化的好文章:
http://www.kubrynski.com/2014/01/understanding-spring-web-initialization.html
ADD 2
根据 Tunaki
的回答,我检查了 AbstractDispatcherServletInitializer
。过滤器注册在以下代码中发生:
即使我覆盖了绿色的 getServletFilters()
方法,我仍然无法访问 registerServletFilter()
的 Dynamic
结果。那么我该如何通过 addMappingForUrlPatterns()
配置过滤器呢?
看来我必须覆盖整个registerDispatcherServlet()
方法。
您可以在应用程序配置中使用以下方式访问registerServletFilter()
的动态结果(具体来说是WebApplicationInitializer):
@Override public void onStartup(ServletContext servletContext) throws ServletException { // Create the 'root' Spring application context AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register( AppConfig.class, SecurityConfiguration.class, HibernateConfiguration.class ); // Add cuatom filters to servletContext FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("recaptchaResponseFilter", new RecaptchaResponseFilter()); filterRegistration.setInitParameter("encoding", "UTF-8"); filterRegistration.setInitParameter("forceEncoding", "true"); filterRegistration.addMappingForUrlPatterns(null, true, "/*"); // Create the dispatcher servlet's Spring application context AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext(); dispatcherServlet.register(MVCConfig.class); // Register and map the dispatcher servlet ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/");
WebMvcConfigurer
是一个接口,用于通过@EnableWebMvc
启用Spring MVC时自定义基于Java的配置。 WebMvcConfigurerAdapter
只是一个适配器,为该接口提供默认的空方法。
它不配置DispatcherServlet
,这就是过滤器使用的内容。因此,您不能使用WebMvcConfigurer
来配置servlet过滤器。
为了轻松配置过滤器,您可以继承自AbstractDispatcherServletInitializer
并覆盖getServletFilters()
:
public class MyWebAppInitializer extends AbstractDispatcherServletInitializer { @Override protected Filter[] getServletFilters() { return new Filter[] { new CharacterEncodingFilter() }; } }
如果您想进一步配置过滤器,则必须改为覆盖onStartup
:
@Override public void onStartup(ServletContext servletContext) throws ServletException { super.onStartup(servletContext); servletContext.addFilter("name", CharacterEncodingFilter.class) .addMappingForUrlPatterns(null, false, "/*"); }