How do I set the default language in Spring 5?

I use three languages in my app:
- English
- Russian
- Estonian (for example)

The language is changed by clicking on the link that ends with: ******/?lang=en, ******/?lang=ee, ******/?lang=ru.

When choosing a different language or writing a random variable, my page is translated to the "default language" (which I set in WebMvcConfig.java), but the variable (in thymeleaf) ${#locale.language} remains the same as it was specified in the URL, that is, when writing in URL ..../?lang=random, in-attribute will be like this: <html ... lang="random">.

Question: How do I make it so that if the user enters a random value of the variable lang in the URL, my program would assign this variable the default language (in my case, ru)?

WebMvcConfig.java:

public class WebMvcConfig implements WebMvcConfigurer {


    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:local/messages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }


    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver resolver = new SessionLocaleResolver();
        resolver.setDefaultLocale(Locale.forLanguageTag("ru"));
        return resolver;
    }

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


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeInterceptor());
    }

}

Main.html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      th:lang="${#locale.language}">

Screenshot

If you need more information, write about it in the comments.

Author: Antonio112009, 2020-01-02

2 answers

Implement your own interceptor based on LocaleChangeInterceptor or HandlerInterceptorAdapter. Add it instead of your default LocaleChangeInterceptor.

You will need to rewrite the preHandle method something like this:

@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        sessionLocaleResolver.setLocale(request, response, Locale.ENGLISH); // здесь будет ваша логика, для примера происходит замена на English при любом значений параметра
        return true;
    }

As you can see from the example, you can specify the logic you need (replacing the language and working with a variable) by rewriting the preHandle method.

 1
Author: Tankred, 2020-01-10 09:02:58

The answer is simple:

Creating a separate file. Let's say LanguageHandler.java. In it we write the following:

public class LanguageHandler extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
        List<String> languages = new ArrayList<>(); //Это нам нужно для проверки языков
        languages.add("ee");
        languages.add("en");
        languages.add("ru");

        //Если указанного языка нет в списке, то, допустим, ставим по дефолта русский
        if(!languages.contains(request.getParameter("lang")) && request.getParameter("lang") != null){
                sessionLocaleResolver.setLocale(request, response, new Locale("ru"));
        }
        return true;
    }
}

In your configurator, you need to add the following line:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /*
    Некоторый код
    */

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        //Некоторый код

        registry.addInterceptor(new LanguageHandler());
    }

}

And now everything will work properly in the HTML file.

Here is an example of the HTML code for Thymeleaf:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      th:lang="${#locale.language}"
>
 1
Author: Antonio112009, 2020-01-10 21:36:49