Ertuğrul Çetin
Ertuğrul Çetin

Reputation: 5231

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.

Upvotes: 5

Views: 2177

Answers (1)

M. Deinum
M. Deinum

Reputation: 124898

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.

Upvotes: 4

Related Questions