Playframework 2.0.1DateFormatter receives system locale

半世苍凉 提交于 2019-12-12 16:36:54

问题


I wrote a custom DateFormatter in Play 2.0 / Java because the default one seems to be i18n-unaware (the implementation details are irrelevant here)

public class DateFormatter extends Formatters.SimpleFormatter<Date>

My application configuration contains

application.langs="pt-br, en"

The languages defined in browser options contain those two (accept-language)

Logically, Lang.preferred(List) returns pt-br as preferred language like in

@Override
public Action onRequest(Request request, Method method) {

    Lang preferred = Lang.preferred(request.acceptLanguages());
    Logger.debug("Preferred language is " + preferred.toLocale());

    return super.onRequest(request, method);
}

BUT (and sadly enough)

the locale received by my custom DateFormatter in

@Override
public Date parse(String date, Locale locale)  {
    ...
}

is system's (JVM) locale, en-US, and not request preferred one.

Is this normal ? What am I missing here ?


回答1:


I think you can use this workaround:

For each request, using the Global interceptor, you can set the LocaleContextHolder to set the Locale of your request:

public class Global extends GlobalSettings {

    @Override
    public Action onRequest(final Request request, Method actionMethod) {
        LocaleContextHolder.setLocaleContext(new LocaleContext() {
            public Locale getLocale() {
                            Lang preferred = Lang.preferred(request.acceptLanguages());
                return preferred.toLocale();
            }
        });
        return super.onRequest(request, actionMethod);
    }

}

I did not test it, but it's worth the shot :-)




回答2:


Sadly the global override mentioned by nico ekito is not reliable solution in Play 2.2, probably because of threads. My experience is that the locale was sometimes improper and the formatter was working unpredictably (sometimes formatting in other language then set in context).

So basically the final solution of John Smith is much more reliable. Instead of using locale passed in the formatter method parameter, use the context locale there:

public Date parse(String date, Locale locale)  {
    Context context = Context.current();
    Lang preferred = Lang.preferred(context.request().acceptLanguages());
    Locale contextLocale = preferred.toLocale()
    ...
}


来源:https://stackoverflow.com/questions/11497470/playframework-2-0-1dateformatter-receives-system-locale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!