JSF 2.0 在整个会话期间从浏览器和以编程方式设置区域设置 [英] JSF 2.0 set locale throughout session from browser and programmatically
问题描述
如何根据初始浏览器请求检测应用程序的语言环境,并在整个浏览会话中使用它,直到用户明确更改语言环境,以及如何在剩余的会话中强制使用此新语言环境?
How do I detect the locale for an application based on the initial browser request and use it throughout the browsing session untill the user specifically changes the locale and how do you force this new locale through the remaining session?
推荐答案
创建一个会话作用域的托管 bean,如下所示:
Create a session scoped managed bean like follows:
@ManagedBean
@SessionScoped
public class LocaleManager {
private Locale locale;
@PostConstruct
public void init() {
locale = FacesContext.getCurrentInstance().getExternalContext().getRequestLocale();
}
public Locale getLocale() {
return locale;
}
public String getLanguage() {
return locale.getLanguage();
}
public void setLanguage(String language) {
locale = new Locale(language);
FacesContext.getCurrentInstance().getViewRoot().setLocale(locale);
}
}
要设置视图的当前区域设置,请将其绑定到主模板的
.
To set the current locale of the views, bind it to the <f:view>
of your master template.
<f:view locale="#{localeManager.locale}">
要更改它,请将其绑定到带有语言选项的
.
To change it, bind it to a <h:selectOneMenu>
with language options.
<h:form>
<h:selectOneMenu value="#{localeManager.language}" onchange="submit()">
<f:selectItem itemValue="en" itemLabel="English" />
<f:selectItem itemValue="nl" itemLabel="Nederlands" />
<f:selectItem itemValue="es" itemLabel="Español" />
</h:selectOneMenu>
</h:form>
为了提高您的国际化页面的 SEO(否则会被标记为重复内容),请将语言也绑定到 .
To improve SEO of your internationalized pages (otherwise it would be marked as duplicate content), bind language to <html>
as well.
<html lang="#{localeManager.language}">
这篇关于JSF 2.0 在整个会话期间从浏览器和以编程方式设置区域设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!