我有这个豆子:
@ManagedBean(name="langListing")
@ViewScoped
public class LangListing implements Serializable
{
private List<SelectItem> languages = new ArrayList<SelectItem>();
private String language;
public LangListing() {
createLangs(); // lazy loading
}
public void createLangs()
{
languages.add(new SelectItem("en", FacesUtil.getResourceBundle().getString("LANG_LABEL_01"))); // English
languages.add(new SelectItem("fr", FacesUtil.getResourceBundle().getString("LANG_LABEL_02"))); // French
}
public List<SelectItem> getLanguages() {
return languages;
}
public String getLanguage()
{
if (FacesContext.getCurrentInstance().getViewRoot().getLocale() != null) {
language = FacesContext.getCurrentInstance().getViewRoot().getLocale().toString();
} else {
language = "en";
}
return language;
}
public void setLanguages(List<SelectItem> languages) {
this.languages = languages;
}
public void setLanguage(String language) {
this.language = language;
}
public void changeLocale(AjaxBehaviorEvent event) {
FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale(getLanguage()));
}
}
我正在调用bean方法:
<h:selectOneMenu id="selectLang" immediate="true" value="#{langListing.language}">
<f:ajax listener="#{langListing.changeLocale}" render="@form" />
<f:selectItems value="#{langListing.languages}" />
</h:selectOneMenu>
问题是我无法获取将语言环境从英语更改为法语的代码。有谁能看到这个问题?请帮忙。
答案 0 :(得分:1)
您设置的值为getLanguage()
,返回当前UIViewRoot
区域设置或仅en
。它不会返回所选的语言值。
您需要修改bean中的逻辑。这是一个重写:
@ManagedBean(name="langListing")
@ViewScoped
public class LangListing implements Serializable {
private List<SelectItem> languages = new ArrayList<SelectItem>();
private String language;
public LangListing() {
languages.add(new SelectItem("en", FacesUtil.getResourceBundle().getString("LANG_LABEL_01"))); // English
languages.add(new SelectItem("fr", FacesUtil.getResourceBundle().getString("LANG_LABEL_02"))); // French
language = FacesContext.getCurrentInstance().getViewRoot().getLocale().toString();
}
public List<SelectItem> getLanguages() {
return languages;
}
public String getLanguage() {
return language;
}
public void setLanguages(List<SelectItem> languages) {
this.languages = languages;
}
public void setLanguage(String language) {
this.language = language;
}
public void changeLocale(AjaxBehaviorEvent event) {
FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale(language));
}
}
请注意,此方法存在更多潜在的漏洞/漏洞。 bean是视图作用域而不是会话作用域,您似乎没有使用<f:view>
(因为它需要Locale
,而不是String
)。我热烈建议您完成this answer以使其与之对齐。