spring internalization language change from controller

2.2k Views Asked by At

In spring internalization i'm using this configuration

@Bean
public LocaleResolver localeResolver() {
    //for this demo, we'll use a SessionLocaleResolver object
    //as the name implies, it stores locale info in the session
    SessionLocaleResolver resolver = new SessionLocaleResolver();

    //default to US locale
    resolver.setDefaultLocale(Locale.US);

    //get out
    return resolver;
}


/**
 * This interceptor allows visitors to change the locale on a per-request basis
 * @return a LocaleChangeInterceptor object
 */
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
    //instantiate the object with an empty constructor
    LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();

    //the request param that we'll use to determine the locale
    interceptor.setParamName("lang");

    //get out
    return interceptor;
}


/**
 * This is where we'll add the intercepter object
 * that handles internationalization
 */
@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(localeChangeInterceptor());
}

And I'm able to change languages from html i.e script and its working fine

window.location.replace('?lang=' + selectedOption);

But is there any way that I can change it from a controller because preferred language will be stored inside DB

so language will be fetched and to be set

example

u = ucr.findByNameContaining(name);
u.getLanguage 
<< i have to set language returned from above line >>

@RequestMapping(value = {"/welcome"}, method = RequestMethod.POST)
public String notificationChannelSearchPost(ModelMap model,HttpSession session
        ,@RequestParam(value="name", defaultValue="") String name) {


     u = ucr.findByNameContaining(name);
     u.getLanguage 
<< i have to set language returned from above line >>
    return "welcom.html";
}

thank you

1

There are 1 best solutions below

1
On

You can set the spring Locale manually in Java by doing something like this

LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);             
localeResolver.setLocale(request, response,new Locale(u.getLanguage()));