本文首发于我的网站:Spring Boot项目中如何定制拦截器java
Servlet 过滤器属于Servlet API,和Spring关系不大。除了使用过滤器包装web请求,Spring MVC还提供HandlerInterceptor(拦截器)工具。根据文档,HandlerInterceptor的功能跟过滤器相似,但拦截器提供更精细的控制能力:在request被响应以前、request被响应以后、视图渲染以前以及request所有结束以后。咱们不能经过拦截器修改request内容,可是能够经过抛出异常(或者返回false)来暂停request的执行。web
Spring MVC中经常使用的拦截器有:LocaleChangeInterceptor(用于国际化配置)和ThemeChangeInterceptor。咱们也能够增长本身定义的拦截器,能够参考这篇文章中提供的demo面试
添加拦截器不只是在WebConfiguration中定义bean,Spring Boot提供了基础类WebMvcConfigurerAdapter,咱们项目中的WebConfiguration类须要继承这个类。spring
修改后完整的WebConfiguration代码以下:apache
package com.test.bookpub;
import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {
@Bean public RemoteIpFilter remoteIpFilter() {
return new RemoteIpFilter();
}
@Bean public LocaleChangeInterceptor localeChangeInterceptor() {
return new LocaleChangeInterceptor();
}
@Override public void addInterceptors(InterceptorRegistry registry {
registry.addInterceptor(localeChangeInterceptor());
}
}复制代码
使用mvn spring-boot:run
运行程序,而后经过httpie访问http://localhost:8080/books?locale=foo
,在终端看到以下错误信息。后端
Servlet.service() for servlet [dispatcherServlet] in context with path []
threw exception [Request processing failed; nested exception is
java.lang.UnsupportedOperationException: Cannot change HTTP accept
header - use a different locale resolution strategy] with root cause复制代码
PS:这里发生错误并非由于咱们输入的locale是错误的,而是由于默认的locale修改策略不容许来自浏览器的请求修改。发生这样的错误说明咱们以前定义的拦截器起做用了。浏览器
在咱们的示例项目中,覆盖并重写了addInterceptors(InterceptorRegistory registory)方法,这是典型的回调函数——利用该函数的参数registry来添加自定义的拦截器。框架
在Spring Boot的自动配置阶段,Spring Boot会扫描全部WebMvcConfigurer的实例,并顺序调用其中的回调函数,这表示:若是咱们想对配置信息作逻辑上的隔离,能够在Spring Boot项目中定义多个WebMvcConfigurer的实例。ide
***本号专一于后端技术、JVM问题排查和优化、Java面试题、我的成长和自我管理等主题,为读者提供一线开发者的工做和成长经验,期待你能在这里有所收获。函数