有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我遵循的是spring国际化的this指南,它是这样实现的LocalResolver

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

但我想通过获取数据库中的用户语言信息来设置defaultLocal,并设置它。我如何才能做到这一点?谢谢你的帮助


共 (3) 个答案

  1. # 1 楼答案

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

    自动连线LocaleResolverHttpServletRequestHttpServletResponse并使用LocaleResolver.setLocale方法:

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

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

  2. # 2 楼答案

    如果您使用spring安全性,这个解决方案可能会对您有所帮助

    国际化配置:

    @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();
        }
    
    }
    
  3. # 3 楼答案

    您可以尝试的一种标准方法是使用HttpHeaders。接受_语言标题。我假设您正在数据库中存储受支持的区域设置,所以为了方便起见,将其移动到属性文件中,因为记录的数量不会太多。那就试试我的方法

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