官术网_书友最值得收藏!

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:

  1. Let's enhance our WebConfiguration class to implement WebMvcConfigurer:
public class WebConfiguration implements WebMvcConfigurer {...} 
  1. Now we will add a @Bean declaration for LocaleChangeInterceptor:
@Bean 
public LocaleChangeInterceptor localeChangeInterceptor() { 
  return new LocaleChangeInterceptor(); 
} 
  1. 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()); 
} 
  1. Start the application by running ./gradlew clean bootRun
  2. In the browser, go to http://localhost:8080/books?locale=foo
  3. 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.
主站蜘蛛池模板: 中阳县| 桐庐县| 洛浦县| 穆棱市| 彰武县| 饶阳县| 昌黎县| 新疆| 东阳市| 义马市| 岳阳市| 湘乡市| 贺州市| 抚顺县| 梓潼县| 凉山| 成武县| 锡林浩特市| 博爱县| 台南县| 年辖:市辖区| 昭苏县| 潍坊市| 吉木乃县| 营口市| 花垣县| 西乌| 昆山市| 台南县| 科技| 广州市| 鄱阳县| 老河口市| 泽库县| 任丘市| 富锦市| 东山县| 巨野县| 闵行区| 深州市| 湾仔区|