如何修复以下错误?开始语是德语。如果我选择英语,它将与德文文本保持不变。然而,如果我选择德语,我得到英语,如果我选择英语,我得到德语。然而,当英语文本代替德语文本出现时,"de“将正确地显示在index.xhtml中的语言(Language de:)旁边。为了显示选择了哪种语言,我在index.xhtml中使用#{index.xhtml}。我使用Apache MyFaces 2.3-next-M6和Quarkus。我做错了什么?
index.xhtml
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui">
<f:view contentType="text/html" encoding="UTF-8" locale="#{language.localeCode}">
<f:loadBundle basename="messages" var="msg" />
<h:head>
<h:outputStylesheet name="primeflex/primeflex.css" />
</h:head>
<h:body>
<p:growl>
<p:autoUpdate />
</p:growl>
<h:form id="formlanguagechanger">
<h:panelGrid columns="2">
Language #{language.localeCode}:
<h:selectOneMenu value="#{language.localeCode}" onchange="submit()"
valueChangeListener="#{language.countryLocaleCodeChanged}">
<f:selectItems value="#{language.countriesInMap}" />
</h:selectOneMenu>
</h:panelGrid>
</h:form>
<h:outputText value="#{msg.title}" />
</h:body>
</f:view>
</html>LanguageBean.java
@Named("language")
@SessionScoped
public class LanguageBean implements Serializable {
private static final long serialVersionUID = 1L;
private String localeCode;
@PostConstruct
public void init() {
localeCode = "de";
}
private static Map<String, Locale> countries;
static {
countries = new LinkedHashMap<String, Locale>();
countries.put("Deutsch", new Locale("de"));
countries.put("English", new Locale("en"));
}
public Map<String, Locale> 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, Locale> entry : countries.entrySet()) {
if (entry.getValue().toString().equals(newLocaleValue)) {
FacesContext.getCurrentInstance().getViewRoot().setLocale((Locale) entry.getValue());
}
}
}
}发布于 2022-01-10 09:57:45
在Mojarra 2.3.17中,这段代码对我很好。
然而,在MyFaces2.3.9中,我可以复制所描述的问题。
根本原因是<f:loadBundle>不是在视图呈现时初始化的,而是仅在视图构建时初始化的。这可能是MyFaces中的一个bug。
我可以通过在<f:loadBundle>中用这个条目替换faces-config.xml标记来解决这个问题。
<application>
...
<resource-bundle>
<base-name>messages</base-name>
<var>msg</var>
</resource-bundle>
</application>至少这不是夸夸斯相关的问题。所以我已经解决了你的问题。
另请参阅:
https://stackoverflow.com/questions/70609500
复制相似问题