接受语言标头和ResourceBundle之间缺少功能

时间:2019-06-24 14:58:06

标签: java java-ee jax-rs

Google foo使我失败了。我想找出是否存在一种标准的“按书”方式,将输入语言环境从“接受语言”标头转换为正确的ResourceBundle。

ResourceBundle::getBundle()方法接受单个语言环境,但是Accept-Language可以具有按索引加权的多个语言环境,例如:de;q=1.0, sl;q=0.9

当前代码:

@Context
private HttpServletRequest request;

public String getString(String key) {
        ResourceBundle i18n = ResourceBundle.getBundle("locale/strings", this.request.getLocale());
        return i18n.getString(key);
}

问题在于getLocale()返回首选语言环境,在这种情况下为de。如果可用资源束是slen,这将尝试找到de,然后回退到en,但实际的预期结果是客户是sl

我的问题基本上是,我是否必须实现遍历HttpServletRequest.getLocales()的自定义后备代码(我不想重新发明轮子。。)还是有更标准,更直接的方法来做到这一点? ?我也会为填补这一空白的一些第三方聚会而安定下来。

到目前为止的自定义解决方案:

@RequestScoped
public class Localization {

    @Context
    private HttpServletRequest request;

    private ResourceBundle i18n;

    @PostConstruct
    void postConstruct() {
        //List of locales from Accept-Language header
        List<Locale> locales = Collections.list(request.getLocales());

        if (locales.isEmpty()) {
            //Fall back to default locale
            locales.add(request.getLocale());
        }

        for (Locale locale : locales) {
            try {
                i18n = ResourceBundle.getBundle("bundles/translations", locale);
                if (!languageEquals(i18n.getLocale(), locale)) {
                    //Default fallback detected
                    //The resource bundle that was returned has different language than the one requested, continue
                    //Only language tag is checked, no support for detecting different regions in this sample
                    continue;
                }
                break;
            }
            catch (MissingResourceException ignore) {
            }
        }
    }

    private boolean languageEquals(Locale first, Locale second) {
        return getISO2Language(first).equalsIgnoreCase(getISO2Language(second));
    }

    private String languageGetISO2(Locale locale) {
        String[] localeStrings = (locale.getLanguage().split("[-_]+"));
        return localeStrings[0];
    }

    public ResourceBundle i18n() {
        return this.i18n;
    }
}

1 个答案:

答案 0 :(得分:0)

我要编写一个拦截器,您可以在其中设置所需的语言,并将所需的逻辑应用于ThreadLocal或将其传递给其他人。

即,您检查可用的语言并定义顺序或设置默认值。

如果使用Spring,则可以手动设置LocaleContextHolder或使用LocaleContextResolver而不是编写自己的拦截器。