21.16.5 拦截器

你可以配置处理器拦截器HandlerInterceptors或web请求拦截器WebRequestInterceptors等拦截器,并配置它们拦截所有进入容器的请求,或限定到符合特定模式的URL路径。

在MVC Java编程配置下注册拦截器的方法:

  1. @Configuration
  2. @EnableWebMvc
  3. public class WebConfig extends WebMvcConfigurerAdapter {
  4. @Override
  5. public void addInterceptors(InterceptorRegistry registry) {
  6. registry.addInterceptor(new LocaleInterceptor());
  7. registry.addInterceptor(new ThemeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");
  8. registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/secure/*");
  9. }
  10. }

在MVC XML命名空间下,则使用<mvc:interceptors>元素:

  1. <mvc:interceptors>
  2. <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
  3. <mvc:interceptor>
  4. <mvc:mapping path="/**"/>
  5. <mvc:exclude-mapping path="/admin/**"/>
  6. <bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor"/>
  7. </mvc:interceptor>
  8. <mvc:interceptor>
  9. <mvc:mapping path="/secure/*"/>
  10. <bean class="org.example.SecurityInterceptor"/>
  11. </mvc:interceptor>
  12. </mvc:interceptors>