Search code examples
javaspring-bootlocalizationinternationalization

What is exact difference between SessionLocaleResolver and FixedLocaleResolver


I am reading about localization and internationalization concepts in Java.

Default Locale can be both SessionLocaleResolver and FixedLocaleResolver.

Setting SessionLocaleResolver as default:

@Bean
public LocaleResolver localeResolver(){
    SessionLocaleResolver r = new SessionLocaleResolver();
    r.setDefaultLocale(Locale.US);
    return r;
}

Setting FixedLocaleResolver as default:

@Bean
public LocaleResolver localeResolver(){
    FixedLocaleResolver r = new FixedLocaleResolver();
    r.setDefaultLocale(Locale.US);
    return r;
}

Can someone tell me what is the exact difference between those two and how does that difference affect an application?


Solution

  • Here is what we can find out from the Spring documentation

    FixedLocaleResolver:

    LocaleResolver implementation that always returns a fixed default locale and optionally time zone. Default is the current JVM's default locale.

    SessionLocaleResolver:

    LocaleResolver implementation that uses a locale attribute in the user's session in case of a custom setting, with a fallback to the specified default locale or the request's accept-header locale. This is most appropriate if the application needs user sessions anyway, i.e. when the HttpSession does not have to be created just for storing the user's locale. The session may optionally contain an associated time zone attribute as well; alternatively, you may specify a default time zone.

    Usually when you want to enable internationalization feature in your Spring Boot application you want to define a second @Bean in your configuration class:

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        return lci;
    }
    

    This together with the SessionLocaleResolver will enable a possibility for a client to send any request with a "lang" parameter to your application, let's say for example to:

    localhost:8080/public/api/?lang=pt_BR

    Which in result will set the session locale attribute from default en_US to pt_BR, which then can be used to change the displayed language on the webpage.

    On the other hand if you will use FixedLocaleResolver and leave LocaleChangeInterceptor as is, then when the client will send a request with "lang" parameter, the server will respond with Http Status 500 Code - Internal Server Error, and you will see in your console that exception was thrown:

    UnsupportedOperationException: Cannot change fixed locale - use a different locale resolution strategy

    So basically FixedLocaleResolver is for cases when you want to upfront disable the possibility of changing locale in your application.