public class LocaleNegotiator extends Object
LocaleNegotiator works by scanning through the client's language preferences (sent by browsers in the Accept-Language header) looking for any language for which there exists is a corresponding resource bundle. When it finds a correspondence, it uses the LocaleToCharsetMap class to determine the charset. If there's any problem, it tries to fall back to US English. The logic currently ignores the client's charset preferences (sent in the Accept-Charset header).
It can be used like this:
String bundleName = "BundleName"; String acceptLanguage = req.getHeader("Accept-Language"); String acceptCharset = req.getHeader("Accept-Charset"); LocaleNegotiator negotiator = new LocaleNegotiator(bundleName, acceptLanguage, acceptCharset); Locale locale = negotiator.getLocale(); String charset = negotiator.getCharset(); ResourceBundle bundle = negotiator.getBundle(); // may be null res.setContentType("text/plain; charset=" + charset); res.setHeader("Content-Language", locale.getLanguage()); res.setHeader("Vary", "Accept-Language"); PrintWriter out = res.getWriter(); out.println(bundle.getString("resource"));
LocaleToCharsetMap
Modifier and Type | Field and Description |
---|---|
private ResourceBundle |
chosenBundle |
private String |
chosenCharset |
private Locale |
chosenLocale |
Constructor and Description |
---|
LocaleNegotiator(String bundleName,
String languages,
String charsets)
Constructs a new LocaleNegotiator for the given bundle name, language
list, and charset list.
|
Modifier and Type | Method and Description |
---|---|
ResourceBundle |
getBundle()
Gets the chosen bundle.
|
private ResourceBundle |
getBundleNoFallback(String bundleName,
Locale loc) |
String |
getCharset()
Gets the chosen charset.
|
protected String |
getCharsetForLocale(Locale loc,
String charsets)
Gets the best charset for a given locale, selecting from a charset list.
|
Locale |
getLocale()
Gets the chosen locale.
|
private Locale |
getLocaleForLanguage(String lang) |
private ResourceBundle chosenBundle
private Locale chosenLocale
private String chosenCharset
public LocaleNegotiator(String bundleName, String languages, String charsets)
bundleName
- the resource bundle namelanguages
- the Accept-Language headercharsets
- the Accept-Charset headerpublic ResourceBundle getBundle()
public String getCharset()
private Locale getLocaleForLanguage(String lang)
private ResourceBundle getBundleNoFallback(String bundleName, Locale loc)
protected String getCharsetForLocale(Locale loc, String charsets)
loc
- the localecharsets
- a comma-separated charset listWebARTS Library Licensed Under the GNU - General Public License. Other Libraries licensed under their respective Open Source Licenses