问题
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)?
The following should work:
- example.com -> english or german, depending on browser settings
- en.example.com -> force english
- de.example.com -> force german
The user should be able to switch between subdomains without losing the session.
Because I have a lot of java controllers, it would be great if the solution works in a centralized place (like Global.java with a filter which may be in scala).
回答1:
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.
来源:https://stackoverflow.com/questions/21786252/playframework-2-2-java-how-to-set-language-i18n-from-subdomain