Sve*_*ven 5 java jsf internationalization jsf-2
我在这里描述的我的JSF应用程序中实现了国际化.
但我遇到了一个问题:当我更改语言环境时,我页面上的所有文本都会发生变化.但是如果我点击导航链接到另一个页面,那么语言环境会跳回到标准语言环境!
我想我在这里想念一些东西.所以我在下面提供了我的代码,希望你能提供帮助:
LocaleBean.java:
@ManagedBean(name="locale")
@SessionScoped
public class LocaleBean {
private Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
public Locale getLocale() {
return locale;
}
public void setLanguage(String language) {
locale = new Locale(language);
FacesContext.getCurrentInstance().getViewRoot().setLocale(locale);
}
public String getLanguage() {
return locale.getLanguage();
}
}
Run Code Online (Sandbox Code Playgroud)
JSF Part(它是我模板的一部分):
<h:outputText value=" #{text['common.language']}: " />
<h:selectOneMenu value="#{locale.language}" onchange="submit()">
<f:selectItem itemValue="de" itemLabel="Deutsch" />
<f:selectItem itemValue="en" itemLabel="English" />
</h:selectOneMenu>
Run Code Online (Sandbox Code Playgroud)
faces-config.xml中:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<application>
<locale-config>
<default-locale>de</default-locale>
<supported-locale>en</supported-locale>
</locale-config>
<resource-bundle>
<base-name>org.dhbw.stg.wwi2008c.mopro.ui.text</base-name>
<var>text</var>
</resource-bundle>
</application>
</faces-config>
Run Code Online (Sandbox Code Playgroud)
然后我从教程中的Text.java,只更改了bundle-path.
这是我的目录:

如果遗漏了重要的东西请求.
FacesContext是请求范围的实例.所以只为该特定请求设置您的值.
添加xhtml
<f:view locale="#{locale.locale}">
Run Code Online (Sandbox Code Playgroud)
要么:
在faces-config.xml中注册一个视图处理程序
<application>
...
<view-handler>com.yourcompany.MyLocaleViewHandler</view-handler>
Run Code Online (Sandbox Code Playgroud)
和
public class MyLocaleViewHandler extends ViewHandler {
private final ViewHandler base;
@Override
public Locale calculateLocale(FacesContext context) {
//fetch the session scoped bean and return the
LocaleBean bean = (LocaleBean ) context.getExternalContext().getRequest().getSession().getAttribute("locale");//this line is not tested.
return locale;
}
//other stuff..
}
Run Code Online (Sandbox Code Playgroud)