有没有办法实现可以更改语言环境的viewParam,例如。
http://example.com/p1.jsf?lang=en 要么 http://example.com/p2.jsf?lang=fr
也许不重复
<f:metadata>
<f:viewParam name="lang" value="#{localeManager.locale}" />
</f:metadata>
在每个xhtml页面中(可能通过拦截每个xhtml请求,检查lang参数的值并更新语言环境)
similar question被问到并回答了但是涉及JSF2 @ManagedProperty,说实话我还是不明白答案。
有什么想法吗?
答案 0 :(得分:0)
我制定了一个不涉及CDI的解决方案。
我在JSF生命周期的恢复视图阶段之后设置了语言环境。
@SuppressWarnings("serial")
public class LifeCycleListener implements PhaseListener {
...
public void afterPhase(PhaseEvent event) {
if (event.getPhaseId() == PhaseId.RESTORE_VIEW) {
// let's try first to get the language from the request parameter
// and if it is a supported language then put it to session
String reqParamLang = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("lang");
if (reqParamLang != null) {
Iterator<Locale> localeIterator = FacesContext.getCurrentInstance().getApplication().getSupportedLocales();
while (localeIterator.hasNext()) {
Locale locale = localeIterator.next();
if (reqParamLang.equals(locale.toString())) {
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("lang", reqParamLang);
Logger.getLogger(this.getClass().getName()).info("will change locale to " + locale);
}
}
}
// get the language from the session and if available then set the locale
String sessionLang = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("lang");
if (sessionLang != null) {
FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale(sessionLang));
}
}
}
}