Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 668
gokhanbirincii Avatar asked Oct 02 '17 07:10

gokhanbirincii


People also ask

Where is the default locale in Spring Boot?

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.

How do I find the default message File in Spring Boot?

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.

How to set fixedlocaleresolver in Spring Boot?

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

How do I change the locale of a spring localeresolver?

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.


1 Answers

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.

like image 90
Cyril Avatar answered Oct 13 '22 18:10

Cyril