Reputation: 33
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
Upvotes: 3
Views: 2483
Reputation: 340
You can optimize your application by retrieving these settings from the application.yml
or application.properties
file. This approach eliminates the need to query the database on every request, improving performance and reducing database load.
Here’s an example of handling i18n (internationalization) in a REST API.
Upvotes: 0
Reputation: 113
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()));
Upvotes: 2