本文首發於我的網站: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面試題、我的成長和自我管理等主題,爲讀者提供一線開發者的工做和成長經驗,期待你能在這裏有所收穫。函數