Spring Boot專案中定製攔截器的方法詳解
這篇文章主要介紹了Spring Boot專案中定製攔截器的方法詳解,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
Servlet 過濾器屬於Servlet API,和Spring關係不大。除了使用過濾器包裝web請求,Spring MVC還提供HandlerInterceptor(攔截器)工具。根據文件,HandlerInterceptor的功能跟過濾器類似,但攔截器提供更精細的控制能力:在request被響應之前、request被響應之後、檢視渲染之前以及request全部結束之後。我們不能通過攔截器修改request內容,但是可以通過丟擲異常(或者返回false)來暫停request的執行。
Spring MVC中常用的攔截器有:LocaleChangeInterceptor(用於國際化配置)和ThemeChangeInterceptor。我們也可以增加自己定義的攔截器,可以參考這篇文章中提供的demo
實戰
新增攔截器不僅是在WebConfiguration中定義bean,Spring Boot提供了基礎類WebMvcConfigurerAdapter,我們專案中的WebConfiguration類需要繼承這個類。
繼承WebMvcConfigurerAdapter;
為LocaleChangeInterceptor新增@Bean定義,這僅僅是定義了一個interceptor spring bean,但是Spring boot不會自動將它加入到呼叫鏈中。
攔截器需要手動加入呼叫鏈。
修改後完整的WebConfiguration程式碼如下:
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的例項。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。