10

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

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
gokhanbirincii
  • 575
  • 5
  • 15

3 Answers3

7

I think you want to set the Locale for the current session, not the default Locale. Assuming there is an existing session (i.e. 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.

Cyril
  • 2,376
  • 16
  • 21
3

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();
}
Varun Sood
  • 201
  • 1
  • 3
  • 8
  • I don’t think that `Locale.LanguageRange.parse(header)` will infer the region from the language variant (region is part of `Locale`). [See here](https://stackoverflow.com/questions/6824157/parse-accept-language-header-in-java#comment84948734_29000266) – Guildenstern Jul 29 '20 at 11:47
1

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

}
mrtasln
  • 574
  • 1
  • 5
  • 18