JSF2国际化的例子

时间:2012-12-28 11:44:12

标签: jsf-2

以此链接的JSF2国际化示例为起点:

http://www.mkyong.com/jsf2/jsf-2-internationalization-example/

我希望这个例子以所选的实际语言显示组合的语言。

有人能指出我如何做到这一点?

谢谢!

1 个答案:

答案 0 :(得分:0)

只需在静态变量countries中设置正确的标签:

static {
    countries = new LinkedHashMap<String,Object>();
    countries.put("English", Locale.ENGLISH); //label, value
    countries.put("Deutsch", Locale.GERMAN);
    countries.put("Français", Locale.FRENCH);
    // ... fill in with additional languages/locales as needed
}

您可以在此处获取原始语言的更大语言名称列表:http://www.omniglot.com/language/names.htm

更新:根据OP的评论,他需要将语言名称翻译成每种语言。为此,人们可以提出一个解决方案,只需制作一张语言地图(这是很多地图),如下所示:

// set a default value for localeCode
private String localeCode = Locale.ENGLISH.toString();
// ...
static {
    countries = new LinkedHashMap<Object, <String,Object>>();
    englishCountries = new LinkedHashMap<String,Object>();
    englishCountries.put("English", Locale.ENGLISH); //label, value
    englishCountries.put("German", Locale.GERMAN);
    englishCountries.put("French", Locale.FRENCH);
    countries.put(Locale.ENGLISH, englishCountries);
    germanCountries = new LinkedHashMap<String,Object>();
    germanCountries.put("Englisch", Locale.ENGLISH);
    germanCountries.put("Deutsch", Locale.GERMAN);
    germanCountries.put("Französisch", Locale.FRENCH);
    countries.put(Locale.GERMAN, germanCountries);
    frenchCountries = new LinkedHashMap<String,Object>();
    frenchCountries.put("Anglais", Locale.ENGLISH);
    frenchCountries.put("Allemand", Locale.GERMAN);
    frenchCountries.put("Français", Locale.FRENCH);
    countries.put(Locale.FRENCH, frenchCountries);
    // ... fill in with additional languages/locales as needed
}

public Map<Object, <String,Object>> getCountriesInMap() {
    return countries;
}

// adapted value change listener from original:
public void countryLocaleCodeChanged(ValueChangeEvent e){
    String newLocaleValue = e.getNewValue().toString(); 
    //loop country map to compare the locale code
    for (Object key : countries.keySet()) {
        if (key.toString().equals(newLocaleValue)) {
            FacesContext.getCurrentInstance().getViewRoot()
                .setLocale((Locale) key);
        }
    }
}

然后你会选择适当的map用于selectItems,如下所示:

<h:selectOneMenu value="#{language.localeCode}" onchange="submit()"
    valueChangeListener="#{language.countryLocaleCodeChanged}">
    <f:selectItems value="#{language.countriesInMap[language.localeCode]}" /> 
</h:selectOneMenu>

注意:不要忘记为language.localeCode设置默认值,否则下拉菜单不会显示任何选项

请注意,这可能是 NOT 对可用性的一个好主意,因为错误选择外语的用户可能很难回到她的已知语言(这就是为什么让列表在每种语言中都有语言名称的好习惯。)