我在寫一個使用Spring Boot的應用程序。在我的應用程序中,我將使用本地化的網址,例如http://localhost:8080/School/**en**/xxx/...
。我嘗試實現Custom Locale Interceptor。在下面列出的第一個變種工作正常。我想使用第二個變體,而不是法國或德國的區域設置不會改變,仍然是en_US。任何人都可以給我建議嗎?創建自定義LocalChangeInterceptor
@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {
1 VARIANT
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(Locale.GERMANY);
return slr;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
lci.setParamName("lang");
return lci;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
2 VARIANT
@Bean
public LangInterceptor langInterceptor() {
return new LangInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(langInterceptor());
}
@Bean
public SessionLocaleResolver sessionLocaleResolver() {
SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
sessionLocaleResolver.setDefaultLocale(Locale.GERMANY);
return sessionLocaleResolver;
}
}
而且我的自定義攔截器:
public class LangInterceptor extends HandlerInterceptorAdapter {
@Autowired
LocaleResolver sessionLocaleResolver;
Locale locale;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (StringUtils.startsWithIgnoreCase(request.getServletPath(), "/it/")) {
locale = new Locale("it");
} else {
locale = new Locale("en");
}
sessionLocaleResolver.setLocale(request, response, Locale.FRENCH);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
我的回答對您有幫助嗎? –
非常感謝,你的解釋是完全真實的,但是: 1. LocaleChangeInterceptor來自'org.springframework.web.servlet.i18n'包,可以使用,它可以作爲所有的第一個變體。 2.第二個變體用xml編寫時適用於我。 –
我需要的確切是我的語言環境將從url –