【问题标题】:how to set defaultLocale programmatically in spring boot如何在spring boot中以编程方式设置defaultLocale
【发布时间】:2018-03-13 06:44:42
【问题描述】:

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

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

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

【问题讨论】:

  • 你没有。 defaultLocale 适用于整个应用程序而不是每个用户。
  • 有没有其他方法可以根据用户偏好确定应用程序语言
  • 这就是本地解析器的全部想法...如果您想使用首选项,请使用您自己的 LocaleResolver 实现。

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


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案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();
    }
    

    【讨论】:

    • 我不认为Locale.LanguageRange.parse(header) 会从语言变体中推断出区域(区域是Locale 的一部分)。 See here
    【解决方案3】:

    如果你使用 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 安全配置:

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

    【讨论】:

      猜你喜欢
      • 2015-09-24
      • 2015-05-03
      • 2019-04-13
      • 2020-03-09
      • 2016-05-22
      • 1970-01-01
      • 2016-05-23
      • 2016-05-03
      • 2017-02-24
      相关资源
      最近更新 更多