如何在Spring Boot中以编程方式设置默认语言环境

10

我正在遵循这个关于Spring国际化的指南,它像这样实现LocalResolver

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

但我想通过在数据库中获取用户语言信息来设置defaultLocal,并将其设置为如何实现?谢谢帮助。


你不需要这样做。defaultLocale 是整个应用程序的语言环境设置,而不是每个用户的设置。 - M. Deinum
1
有没有其他方法可以根据用户偏好确定应用程序语言? - gokhanbirincii
1
这就是本地解析器的整个思想...如果你想使用偏好设置,请使用自己的LocaleResolver实现。 - M. Deinum
3个回答

7

我认为您想要设置当前会话的Locale,而不是默认的Locale。假设存在一个现有的会话(即用户登录后):

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

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

这将设置当前会话的语言环境。


3

您可以尝试使用HttpHeaders.ACCEPT_LANGUAGE头来采用一种标准的方法。我假设您正在将支持的语言环境存储在数据库中,为了方便起见,请将其移动到属性文件中,因为记录数量不会太多。然后按照以下方式尝试我的方法。

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();
}

我认为 Locale.LanguageRange.parse(header) 不会从语言变体中推断出地区(地区是 Locale 的一部分)。 点击这里 查看详情。 - Guildenstern

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();
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接