如何在spring boot中以编程方式设置defaultLocale

时间:2017-10-02 07:45:46

标签: java spring spring-mvc spring-boot internationalization

我正在关注this春季国际化指南,它实现了LocalResolver这样的

@Bean
public LocaleResolver localeResolver() {
    SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
    sessionLocaleResolver.setDefaultLocale(Locale.US);
    return sessionLocaleResolver;
}

但我想通过在数据库中获取用户语言信息来设置defaultLocal并设置它我该怎么做?谢谢你的帮助

3 个答案:

答案 0 :(得分:2)

您可以尝试的一种标准方法是使用HttpHeaders.ACCEPT_LANGUAGE标头。我假设您在DB中存储支持的语言环境,因此对于客户将其移动到属性文件,因为记录数量不会很多。然后尝试我的方法

public Locale resolveLocale(HttpServletRequest request) {
    String header = request.getHeader(HttpHeaders.ACCEPT_LANGUAGE);
    List<Locale.LanguageRange> ranges =  Locale.LanguageRange.parse(header);
    return findMatchingLocale(ranges);
}

public Locale findMatchingLocale(List<Locale.LanguageRange> lang) {
    Locale best = Locale.lookup(lang, supportedLocale); // you can get supported from properties file , we maintaining list of supported locale in properties file
    String country = findCountry(lang);
    return new Locale(best.getLanguage(), country);
}

public String findCountry(List<Locale.LanguageRange> ranges) {
    Locale first = Locale.forLanguageTag(ranges.get(0).getRange());
    first.getISO3Country();
    return first.getCountry();
}

答案 1 :(得分:2)

我认为您要为当前会话设置区域设置,而不是默认区域设置。 假设存在会话(即在用户登录后):

自动装配LocaleResolverHttpServletRequestHttpServletResponse并使用LocaleResolver.setLocale方法:

    Locale userLocale = getLocaleByUsername(username); //load from DB
    localeResolver.setLocale(httpServletRequest, httpServletResponse, userLocale);

这将设置当前会话的区域设置。

答案 2 :(得分:1)

如果您使用spring security,也许此解决方案可以帮助您。

国际化配置:

@Configuration
@EnableAutoConfiguration
public class InternationalizationConfig extends WebMvcConfigurerAdapter {


    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(new Locale("tr"));//Locale.forLanguageTag("tr"));//
//      slr.setDefaultLocale(Locale.forLanguageTag("tr"));
        return slr;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        return lci;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }

}

Spring Security配置:

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling().accessDeniedPage("/login")
                .and()
                .formLogin().loginPage("/index")
                .usernameParameter("username")
                .passwordParameter("password")
                .loginProcessingUrl("/j_spring_security_check")
                .failureUrl("/loginFail")
                .defaultSuccessUrl("/loginSuccess")
                .and()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/index")
                ;
        http.headers().frameOptions().disable();
    }

}

控制器:

@Controller
public class LoginController {

    @RequestMapping("/loginSuccess")
    public String loginSuccess(){

        User user = getUserFromDatabase; 

       return "redirect:/home?lang="+user.getLanguage();
    }

}