一口一口喫掉Struts(九)——國際化問題(2) .

Strust如何支持國際化?

 

(一)頁面jsp)靜態信息的國際化

 

我們以登錄這個例子來說明。

 

通過點擊中文或英文,實現登錄界面語言信息的改變

 

主要步驟:

 

1、創建國際化資源文件

 

*與上一篇中提到的創建方式一致

屬性文件內容

MessagesBoundle_zn_CN.properties

 

login.form.field.username=\u7528\u6237                          ----如果爲GBK編碼,這裏是“用戶名”

login.form.field.password=\u5BC6\u7801                                                                                “密碼”

login.form.button.login=\u767B\u5F55                                                                                      “登錄”

 

我們看到並非爲中文,而是unicode編碼。

這是採用JAVA_HOME/bin/native2ascii工具轉換的,不然會出現亂碼

 

MessagesBoundle_en_US.properties

 

login.form.field.username=user name

login.form.field.password=password

login.form.button.login=login

 

 

2、需要在struts配置文件中指定資源屬性文件的位置和名稱,如<message-resources parameter="MessageResources" />

 

*Parameter=國際化資源文件的basename即可

 

3、在JSP頁面中使用Struts標籤庫來實現顯示,如<bean:message key=“key string”/>來輸出文本

 

*需要引入相應的標籤庫<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>

 

*struts利用在session中存放一個Locale對象來達到設置當前語言的目的
*默認的情況下,struts根據網頁向後臺提交時所包含的語言編碼信息來提供缺省的Locale對象,這就是我們爲什麼可以通過更改網頁顯示語言設置,就能顯示不同的語言文字的原因。
*strutssession中存放的這個Locale對象,取名爲:Globals.LOCALE_KEY的值,Globalsstruts框架提供的一個對象

利用這個原理,我們可以用編程的方式來手工切換整個應用系統的語言

 

示例:

相關action

<action path="/changeLanguage" type="com.jialin.ChangeLanguageAction"
		scope="request">
		<forward name="login" path="/index.jsp" />
</action>
public class ChangeLanguageAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		String lang = request.getParameter("lang");
		Locale locale = Locale.getDefault();
		
		if ("zh".equals(lang)) {
			locale = new Locale("zh", "CN"); 
		}else if ("en".equals(lang)) {
			locale = new Locale("en", "US");
		}
		
		this.setLocale(request, locale);//將語言信息設置到session中		
		return mapping.findForward("login");
	}
	
}


登錄JSP

<body>
   <form action="login.do" method="post">
	<bean:message key="login.form.field.username" />
	<input type="text" name="name" />
	<br />
	<bean:message key="login.form.field.password" />
	<input type="password" name="password" />
	<input type="submit" value="<bean:message key="login.form.button.login"/>" />
   </form>

	<a href="changeLanguage.do?lang=zh">中文</a>    
	<a href="changeLanguage.do?lang=en">英文</a>
</body>

 

頁面信息的國際化還可以給我們帶來另一個好處:我們可以通過修改國際化資源文件更改頁面顯示的內容,今天叫登錄,明天可以改爲開始等等。


(二)動態消息的國際化

對於消息提示,異常信息等這些動態信息,我們如何實現國際化呢?

 

我們依然用上面的例子,在登錄驗證中加入國際化

 

更改MessagesBoundle_zn_CN.properties

errors.header=<UL>
errors.prefix=<font color="red"><LI>
errors.suffix=</LI></font>
errors.footer=</UL>
login.form.field.username=\u7528\u6237
login.form.field.password=\u5BC6\u7801
login.form.button.login=\u767B\u5F55
login.success={0},\u767B\u5F55\u6210\u529F                                                                                                                                                 --登錄成功
login.user.not.found=\u7528\u6237\u4E0D\u80FD\u627E\u5230\uFF0C\u7528\u6237\u540D\u79F0\=\u3010{0}\u3011                   --用戶未找到,用戶=
login.password.error=\u5BC6\u7801\u9519\u8BEF                                                                                                                                            --密碼錯誤

更改MessagesBoundle_en_US.properties

errors.header=<UL>
errors.prefix=<font color="red"><LI>
errors.suffix=</LI></font>
errors.footer=</UL>
login.form.field.username=user name
login.form.field.password=password
login.form.button.login=login
login.success={0},Login Success
login.user.not.found=user not found,user name=[{0}]
login.password.error=password error

Struts配置文件

<struts-config>

	<!-- set ActionForm info-->
	<form-beans>
		<form-bean name="userForm" type="com.jialin.UserActionForm" />
	</form-beans>
	
	<global-forwards>
		<forward name="login" path="/index.jsp" />
		<forward name="success" path="/LoginSuccess.jsp" />
		<forward name="fail" path="/LoginFail.jsp" />
	</global-forwards>
	
	<action-mappings>
		<!-- Set path,action,actionform,scope,forward info -->
		<action path="/login" type="com.jialin.LoginAction" name="userForm"
			scope="request" validate="true" attribute="uf">
		</action>

		<action path="/changeLanguage" type="com.jialin.ChangeLanguageAction"
			scope="request">
		</action>
	</action-mappings>

	<message-resources parameter="com.jialin.resource.MessagesBoundle"></message-resources>

</struts-config>


LoginAction

 

第一步:在這個LoginAction中,我們將根據業務邏輯需要獲取國際化消息文本ActionMessage,然後將他保存起來到ActionMessages裏

 

ActionMessagesActionMessage對象
*ActionMessages對象是ActionMessage對象的集合
*一個ActionMessage對象,代表一個國際化消息文本(字符串)

 

第二步:保存這個ActionMessages,用於傳遞

 

首先我們要判斷要傳遞的消息是普通消息還是錯誤消息?

*普通消息:即普通的消息文本

*錯誤消息:即異常消息文本

本質上,這兩種消息沒有什麼區別,都是消息文本,但是如果一個頁面同時需要顯示普通的消息文本和錯誤消息文本的時候,就需要進行區分了,比如不同類型的消息文本可能要用不同的樣式來顯示

 

 

/**
 * 登錄action
 * @author jialin
 *作用:取得表單數據,調用model層業務邏輯,返回轉向信息
 */
public class LoginAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		UserActionForm  userForm=(UserActionForm)form;
		String userName=userForm.getName();
		int password=userForm.getPassword();  //這裏不用我們手動強轉類型了。
		
		UserManage userManage=new UserManage();
		User user=new User();
		user.setName(userName);
		user.setPassword(password);
		ActionMessages messages = new ActionMessages();
		
		
		try {
			userManage.ValidateUser(user);
			//創建國際化消息文本
			ActionMessage message=new ActionMessage("login.success", userName);
			messages.add("login_message_1",message);
			
			//傳遞國際化消息,普通消息
			this.saveMessages(request, messages);
			
			return mapping.findForward("success");
		
		} catch (UserNotFoundException e) {
			//創建國際化消息文本
			ActionMessage message=new ActionMessage("login.user.not.found", userName);
			messages.add("login_error_1",message);
			
			//傳遞國際化消息,異常消息
			this.saveErrors(request, messages);
			
		}catch (PasswordErrorException e) {
			//創建國際化消息文本
			ActionMessage message=new ActionMessage("login.password.error", userName);
			messages.add("login_error_2",message);
			
			//傳遞國際化消息,異常消息
			this.saveErrors(request, messages);
		}
		
		return mapping.findForward("fail");
		
	}

}

UserManage

/**
 * MODEL層業務邏輯
 * 
 * @author jialin 判斷用戶是否合法
 */
public class UserManage {

	public void ValidateUser(User user) {
		// 判斷用戶名密碼是否正確
		if (!"jialin".equals(user.getName())) {
			//"用戶不存在!用戶名爲:" + user.getName()"會被Struts用於填充佔位符
			throw new UserNotFoundException("用戶不存在!用戶名爲:" + user.getName());
		} else if (user.getPassword() != 123456) {
			//"密碼錯誤“會被Struts用於填充佔位符
			throw new PasswordErrorException("密碼錯誤");
		}
	}
}

 

自定義異常類PasswordErrorException,UserNotFoundException略

 

登錄失敗jsp

	<body>
		<font color="red"> <html:messages id="msg"
				property="login_error_1">
				<bean:write name="msg" />
			</html:messages> </font>
		<font color="blue"> <html:messages id="msg"
				property="login_error_2">
				<bean:write name="msg" />
			</html:messages> </font>
	</body>

 

別忘記引入taglib

<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>

 

也可以用 <html:errors />代替<font color="red"> <html:messages id="msg"property="login_error_1"><bean:write name="msg" /></html:messages> </font><font color="blue"> <html:messages id="msg"property="login_error_2"><bean:write name="msg" /></html:messages> </font>顯示異常信息

<html:errors/>標籤只顯示錯誤消息
<html:errors/>標籤與<html:messages/>標籤類似,但無id屬性
<html:errors/>標籤通過提供header/footer屬性以及prefix/suffix屬性來定製每條消息的顯示格式
header/footer – 定義整個錯誤消息顯示之前(之後)要顯示的內容,這些內容也是在資源屬性文件中定義的一些key值,默認的情況下,它們的取值分別爲:errors.header和errors.footer
prefix/suffix – 定義每條錯誤消息顯示之前(之後)要顯示的內容,這些內容也是在資源屬性文件中定義的一些key值,默認的情況下,它們的取值分別爲:errors.prefix和errors.suffix
舉例如下(見國際化資源文件):

errors.header=<UL>

errors.prefix=<LI>

errors.suffix=</LI>

errors.footer=</UL>

 


 

登錄成功jsp

<body>
		<html:messages id="msg" message="true">
			<bean:write name="msg" />
		</html:messages>
	</body>



效果就貼圖了,下篇接着說struts對異常的處理

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章