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
By default, a Spring Boot application will look for message files containing internationalization keys and values in the src/main/resources folder. The file for the default locale will have the name messages.properties, and files for each locale will be named messages_XX.properties, where XX is the locale code.
5. Defining the Message Sources By default, a Spring Boot application will look for message files containing internationalization keys and values in the src/main/resources folder. The file for the default locale will have the name messages.properties, and files for each locale will be named messages_XX.properties, where XX is the locale code.
@SpringBootApplication public class Main { @Bean public LocaleResolver localeResolver() { SessionLocaleResolver r = new SessionLocaleResolver(); r.setDefaultLocale(Locale.US); return r; } ... } Spring boot by default auto configures AcceptHeaderLocaleResolver. It also allows to set FixedLocaleResolver as following two properties:
Good news is, Spring already provides such an interceptor: LocaleChangeInterceptor. This interceptor can change the current locale of underlying LocaleResolver on every request only if a specified request parameter (set by LocaleChangeInterceptor.setParamName (..)) is present in the HTTP request.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With