0
votes

This is my first time I am working with spring boot and thymeleaf. I got 2 pages on my application. A page with all cars and a config page for a specific car.

In my header I got a select box where the language can be changed. This appears on both pages. When I change the language I get a localeResolver that changes the language. I got 2 message.properties files for the 2 languages.

If I for example choose English the page is reloading with the English language. Then when I click on a car to go to that specific car config page it still remembers what language to use. But on the config page you can change the language as well in the header. If I click on for example Dutch it is working also.

But if I go to the previous page it still has the old url with localhost:9000/locale?lang=en_GB instead of localhost:9000/locale?lang=nl_NL.

When I return a view from a controller I want it to return it with the language.

This is my webMvcConfig

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(localeChangeInterceptor());
    registry.addInterceptor(new ThymeLeafLayoutInterceptor());
}

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

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

This is my controller that returns the view search.html

 @RequestMapping(method = RequestMethod.GET)
public String search() {
    return "search";
}

How do I return the view with a language parameter. So for example: localhost:9000/locale?lang=en_GB

1

1 Answers

0
votes

I think you press go back button (←) of the browser. If that's the case it's not a problem at all.
Just remember to avoid providing too much functionality for your program.
You will just clutter your application with unnecessary code.

How often would a user choose a language in page 1, then goes to page 2, chooses another language there and then presses go back button of the browser?!

However, if you really need to add query parameters yourself, you should redirect to a new page as stated in this answer (which causes the client browser to send a new request to you):

return "redirect:YOUR_PAGE_URL?lang=en_GB";

You can also get the current locale in your controller method if that helps:

Locale locale = LocaleContextHolder.getLocale();
return "redirect:YOUR_PAGE_URL?lang=" + locale;