- Spring Boot 2.0 Cookbook(Second Edition)
- Alex Antonov
- 221字
- 2021-06-24 19:24:41
How to do it...
Despite what you might think, after seeing the previous recipe, adding an interceptor is not as straightforward as just declaring it as a bean. We actually need to do it via WebMvcConfigurer or by overriding WebMvcConfigurationSupport. Let's take a look at the following steps:
- Let's enhance our WebConfiguration class to implement WebMvcConfigurer:
public class WebConfiguration implements WebMvcConfigurer {...}
- Now we will add a @Bean declaration for LocaleChangeInterceptor:
@Bean public LocaleChangeInterceptor localeChangeInterceptor() { return new LocaleChangeInterceptor(); }
- This will actually create the interceptor Spring bean, but will not add it to the request handling chain. For this to happen, we will need to override the addInterceptors method and add our interceptor to the provided registry:
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); }
- Start the application by running ./gradlew clean bootRun
- In the browser, go to http://localhost:8080/books?locale=foo
- Now, if you look at the console logs, you will see a bunch of stack trace errors basically saying the following:
Caused by: java.lang.UnsupportedOperationException: Cannot change HTTP accept header - use a different locale resolution strategy
While the error is not because we entered an invalid locale, but because the default locale resolution strategy does not allow the resetting of the locale that is requested by the browser, the fact that we got an error shows that our interceptor is working.
推薦閱讀
- 大數據可視化
- 商業分析思維與實踐:用數據分析解決商業問題
- Dependency Injection with AngularJS
- MySQL 8.x從入門到精通(視頻教學版)
- 數據庫原理與設計(第2版)
- Oracle RAC日記
- Mastering LOB Development for Silverlight 5:A Case Study in Action
- 新手學會計(2013-2014實戰升級版)
- 區域云計算和大數據產業發展:浙江樣板
- Hadoop 3實戰指南
- 大數據技術原理與應用:概念、存儲、處理、分析與應用
- 計算機視覺
- The Natural Language Processing Workshop
- 改進的群智能算法及其應用
- 數字化轉型實踐:構建云原生大數據平臺