playframework 2.2 java: how to set language (i18n) from subdomain

前端 未结 1 652
逝去的感伤
逝去的感伤 2021-01-06 11:22

How can I set the language (i18n) not only from the users browser settings but also from subdomains (which should have higher priority) in playframework 2.2 (java)?

1条回答
  •  时光说笑
    2021-01-06 11:31

    You can use i.e. changeLang(String code) method of play.mvc.Controller superclass for this.

    Then you need to tell to your language resolver, which domain uses which language us default, probebly using application.conf or databse records for this. Next depending on what you want to achieve, just use Global class to intercept all your request, or create a simple action which will change the language and they will return to the same page (so user can decide himself which language he wants to use).

    It's some kind of cookie based machanism, so I'm not sure if it isn't required to perform forced page reload (ie. by redirecting to the same path) anyway I assume that you will tell us when you'll check it ;)

    Edit:

    that could be ie. like

    public Action onRequest(final Http.Request request, final Method actionMethod) {
    
        if (request.host().equals("de.yourdomain.tld")
                && (request.cookie("PLAY_LANG") == null || !request.cookie("PLAY_LANG").value().equals("de"))) {
            return new Action.Simple() {
                public Result call(Http.Context ctx) throws Throwable {
                    ctx.changeLang("de");
                    return redirect(request.path());
                }
            };
        } else {
            return super.onRequest(request, actionMethod);
        }
    }
    

    Just make sure that you have de lang added in application.conf, otherwise you'll get beautiful, endless redirection loop. the PLAY_LANG is typical Play's cookie name for storing selected language.

    0 讨论(0)
提交回复
热议问题