几个关键的地方:
- 建立中文和英文的语言环境资源文件:
- 切换语言环境的链接,这里调用了FuncBean后台Bean的changLangEnv事件处理方法:
<h:form> <h:commandLink actionListener="#{FuncBean.changLangEnv}" value="中文" /> <h:commandLink actionListener="#{FuncBean.changLangEnv}" value="English" /> </h:form>
- 实现事件监听器,利用ActionEvent 的getComponent来获取事件源,利用FacesContext对象获取视图,并设置视图的语言环境,注意这里的语言常量(Locale.US和Locale.CHINESE):
public void changLangEnv(ActionEvent ae){
HtmlCommandLink hlink=(HtmlCommandLink)ae.getComponent();
String lang=(String)hlink.getValue();
if(lang.equals("English")){
FacesContext.getCurrentInstance().getViewRoot().setLocale(Locale.US);
}else if(lang.equals("中文")){
FacesContext.getCurrentInstance().getViewRoot().setLocale(Locale.CHINESE);
}
}
jsf页面源码:
<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%-- This file is an entry point for JavaServer Faces application. --%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <f:view> <f:loadBundle var="CusMes" basename="com.xgtimes.CustomMessages" /> <h1><h:outputText value="#{CusMes.appName}" /></h1> <hr /> <h:form> <h:commandLink actionListener="#{FuncBean.changLangEnv}" value="中文" /> <h:outputLabel value=" "/><h:outputLabel value=" "/> <h:commandLink actionListener="#{FuncBean.changLangEnv}" value="English" /> </h:form> <br /> <h:form> <h:inputText id="inputTxt"> <h:outputLabel value="#{CusMes.inputTxtLabel}"/> <f:validateLength minimum="3" maximum="10" /> </h:inputText> <h:commandButton id="okcom" type="submit" value="#{CusMes.okcomCaption}"></h:commandButton><br> <h:messages /> </h:form> </f:view> </body> </html>
后台Bean(FuncBean)源码:
package com.xgtimes; import java.util.Locale; import javax.faces.component.html.HtmlCommandLink; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; public class FuncBean { public FuncBean() { } public void changLangEnv(ActionEvent ae){ HtmlCommandLink hlink=(HtmlCommandLink)ae.getComponent(); String lang=(String)hlink.getValue(); if(lang.equals("English")){ FacesContext.getCurrentInstance().getViewRoot().setLocale(Locale.US); }else if(lang.equals("中文")){ FacesContext.getCurrentInstance().getViewRoot().setLocale(Locale.CHINESE); } } }