简体   繁体   中英

How to propagate a JSF locale to other layers in the application

In Java Server Faces, we normally get the locale of the current request with the UIViewRoot.getLocale() method, which would normally return the locale set in the browser. In a layered application, how can I read the same locale in other layers, where there's no access to the JSF objects? It seems that Locale.getDefault() is not suitable, because it returns a JVM-wide default locale. I need the context locale, set only by the current request from the browser. I assume it needs to have some kind of thread-affinity, like with .NET's Thread.CurrentCulture property.

Not really the answer you probably expect, but in a layered design the answer should be: you don't.

Only the presentation layer is supposed to do data formatting according to the locale.

The business layer and the data layer should hold and manipulate data in locale-independent fashion.

You can pass it as an argument to methods that need it. This is, I think, the best approach.

public void businessMethod(String someArg, int otherArg, Locale locale) {
   ..
}

It however requires modifying your method signatures. You can implement something like in .NET via:

public final class LocaleProvider {
    private static ThreadLoca<Locale> currentLocale;
    //static setters and getters for the threadLocal
}

But this is essentially what FacesContext.get....getLocale() is doing. So except for getting rid of the dependencies on JSF in your service layer, you are not doing much more.

That said, current Locale should rarely be needed in the business operations. Two examples I can think of:

  • sending emails (the appropriate template should be chosen)
  • generating documents (like pdf) in the appropriate language

So, think twice before you include a locale dependency in your business-logic.

Locale is oriented only for web layer; service layer and dao layer should use a custom Language domain object. For templates, emails, etc convert Locale into Language or use a default language.

Think this: what happens if I call a web service which will call a service that uses locale? Locale will be null!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM