JSF2中实现国际化
每一个MVC框架都实现了国际化功能,使用这些国际化功能都差不多,在JSF2中实现国际化也非常的简单
1.定义一个ManagedBean来管理语言,并添加一个语言修改的监听方法,在语言修改的时候触发。
2.在faces-config中配置这个语言Bean。
3.在页面添加相应的HTML组件以及添加监听器。
LanguageBean:
public class LanguageBean {
private static final long serialVersionUID = 1L;
private static String localeCode;
private static Map<String, Object> countries;
static {
countries = new LinkedHashMap<String, Object>();
countries.put(ContextUtil.getI18NMessage(FacesContext.getCurrentInstance(), "#{msg.english}"), Locale.ENGLISH); // label, value
countries.put(ContextUtil.getI18NMessage(FacesContext.getCurrentInstance(), "#{msg.chinese}"), Locale.SIMPLIFIED_CHINESE);
}
public Map<String, Object> getCountriesInMap() {
return countries;
}
public String getLocaleCode() {
return localeCode;
}
public void setLocaleCode(String localeCode) {
this.localeCode = localeCode;
}
// value change event listener
public void countryLocaleCodeChanged(ValueChangeEvent e) {
String newLocaleValue = e.getNewValue().toString();
// loop country map to compare the locale code
for (Map.Entry<String, Object> entry : countries.entrySet()) {
if (entry.getValue().toString().equals(newLocaleValue)) {
FacesContext.getCurrentInstance().getViewRoot()
.setLocale((Locale) entry.getValue());
countries = new LinkedHashMap<String, Object>();
countries.put(ContextUtil.getI18NMessage(FacesContext.getCurrentInstance(), "#{msg.english}"), Locale.ENGLISH); // label, value
countries.put(ContextUtil.getI18NMessage(FacesContext.getCurrentInstance(), "#{msg.chinese}"), Locale.SIMPLIFIED_CHINESE);
}
}
}
}
faces-config.xml中的配置:
<managed-bean>
<managed-bean-name>language</managed-bean-name>
<managed-bean-class>com.bond.bean.LanguageBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<application>
<locale-config>
<default-locale>en</default-locale>
</locale-config>
<resource-bundle>
<base-name>bean.properties.bean</base-name>
<var>msg</var>
</resource-bundle>
</application>
这里的scope为Session
页面上的组件:
<h:outputLabel value="#{msg.language}"></h:outputLabel>
<h:selectOneMenu value="#{language.localeCode}" onchange="submit();"
valueChangeListener="#{language.countryLocaleCodeChanged}">
<f:selectItems value="#{language.countriesInMap}" />
</h:selectOneMenu>
这样,简单的国际化就实现了。