简体   繁体   中英

how to set defaultLocale programmatically in spring boot

I am following this guide for spring internationalization it implements LocalResolver like this

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

but I want to set defaultLocal by getting user language information in database and set it how can I do that? thanks for help

One standard approach you can try is using HttpHeaders.ACCEPT_LANGUAGE header. I assume you are storing supported locales in DB , so for conviniece move it to properties file , as number of records wont be many. Then try my approach like this

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

I think you want to set the Locale for the current session, not the default Locale. Assuming there is an existing session (ie after user login):

Autowire LocaleResolver , HttpServletRequest and HttpServletResponse and use the LocaleResolver.setLocale method:

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

This will set the Locale for the current session.

If you use spring security ,maybe this solution help you.

Internationalization config :

@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 config:

@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 :

@Controller
public class LoginController {

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

        User user = getUserFromDatabase; 

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM