Spring MVC: redirect user according to browser language

2.2k views Asked by At

In Spring MVC 4 how can I redirect the user to a localized url according to the browser language (the HTTP header "Accept-Language")?

I would that if an user is trying to access the url example.com/some/path it will redirect to de.example.com/some/path if its browser language is "DE" (i.e. the "Accept-Language" header is set to "de").

In the same way, if an user is accessing de.example.com/some/path and its language is EN it should be redirected to example.com/some/path.

What is the easiest way to get that?

2

There are 2 answers

1
Neil McGuigan On

Create a HandlerInterceptor (extend HandlerInterceptorAdapter) and get the Accept-Language header from the Request. You need to register your Interceptor in your Web Application Context Config.

You also want to know what domain your server is running on. See How to get domain URL and application name?

You should allow the user to change their locale (they might want your site in German even if browser is set to en_US). So you'd need to set a cookie in this case. See LocaleChangeInterceptor too.

2
holmis83 On

What about something like this in your controller:

@RequestMapping("/path")
public String someMapping(Locale locale) {
    if ("de".equals(locale.getLanguage())) {
        return "redirect:http://de.example.com/some/path";
    }
}

Note that language codes are written in lowercase.