Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Internationalization by subdomain in Spring Boot

I'm trying to create spring boot (multi-lang) web app.

Let say user access from this domain: "en.mywebsite.com/index.html" -> English lang will be initiated.

from this domain: "fr.mywebsite.com/index.html" -> French lang will be initiated.

How can I achieve this? I also looked up this blog post but there is no additional info about sub domains.

like image 235
Ertuğrul Çetin Avatar asked Sep 29 '22 03:09

Ertuğrul Çetin


1 Answers

Something like the following would do the trick.

public class SubDomainLocaleResolver extends AbstractLocaleResolver {


    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String domain = request.getServerName();
        String language = domain.substring(0, domain.indexOf('.'));
        Locale  locale = StringUtils.parseLocaleString(language);
        if (locale == null) {
            locale = determineDefaultLocale(request);
        }
        return locale != null ? locale : determineDefaultLocale(request);
    }

    protected Locale determineDefaultLocale(HttpServletRequest request) {
        Locale defaultLocale = getDefaultLocale();
        if (defaultLocale == null) {
            defaultLocale = request.getLocale();
        }
        return defaultLocale;
    }    

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
        throw new UnsupportedOperationException("Cannot change sub-domain locale - use a different locale resolution strategy");

    }
}

You get the server name, parse the first part and try to resolve a Locale in none found you can get the default.

like image 66
M. Deinum Avatar answered Oct 13 '22 11:10

M. Deinum