? ? Struts提供了國際化的功能,對于一個面向各國的系統來說,是非常有幫助的。只需要提供每個國家的語言資源包,配置后即可使用。
? ? 下面來用一個登錄實例來演示一下Struts的國際化配置和顯示。
? ? 創建一個login_i18n_exception的javaweb項目,引入Struts的所有jar包以及jstl.jar和standard.jar。登錄界面無非就是輸入用戶名,密碼,所以ActionForm中只需要設置2個屬性即可。
~~~
package com.bjpowernode.struts;
import org.apache.struts.action.ActionForm;
/**
* 登錄ActionForm,負責收集表單數據
* 表單的數據必須和ActionForm的get,set一致
* @author Longxuan
*
*/
@SuppressWarnings("serial")
public class LoginActionForm extends ActionForm {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
~~~
? ? 登錄時會驗證密碼是否正確,需要提供異常處理,本實例顯示2個異常:用戶名未找到,密碼錯誤。
~~~
package com.bjpowernode.struts;
/**
* 密碼錯誤異常
* @author Longxuan
*
*/
@SuppressWarnings("serial")
public class PasswordErrorException extends RuntimeException {
public PasswordErrorException() {
// TODO Auto-generated constructor stub
}
public PasswordErrorException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public PasswordErrorException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
public PasswordErrorException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public PasswordErrorException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
}
}
package com.bjpowernode.struts;
/**
* 用戶未找到異常
* @author Longxuan
*
*/
@SuppressWarnings("serial")
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException() {
// TODO Auto-generated constructor stub
}
public UserNotFoundException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public UserNotFoundException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
public UserNotFoundException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public UserNotFoundException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
}
}
~~~
? ? 提供用戶管理類,處理用戶的相關操作,這里主要處理用戶登錄:
~~~
package com.bjpowernode.struts;
/**
* 用戶管理類
* @author Longxuan
*
*/
public class UserManager {
/**
* 簡單處理登錄邏輯
* @param username 用戶名
* @param password 密碼
*/
public void login(String username,String password){
if(!"admin".equals(username)){
throw new UserNotFoundException();
}
if(! "admin".equals(password)){
throw new PasswordErrorException();
}
}
}
~~~
? ? 現在寫LoginAction的處理:
~~~
package com.bjpowernode.struts;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
/**
* 登錄Action 負責取得表單數據,調用業務邏輯,返回轉向信息
*
* @author Longxuan
*
*/
public class LoginAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//獲取數據
LoginActionForm laf = (LoginActionForm) form;
String username = laf.getUsername();
String password = laf.getPassword();
UserManager userManager = new UserManager();
ActionMessages messages = new ActionMessages();
try {
//用戶登錄
userManager.login(username, password);
//獲取登錄成功的國際化消息
ActionMessage success= new ActionMessage("login.success",username);
messages.add("login_success_1",success);
//傳遞消息
this.saveMessages(request, messages);
return mapping.findForward("success");
} catch (UserNotFoundException e) {
e.printStackTrace();
//獲取登錄成功的國際化消息
ActionMessage error = new ActionMessage("login.user.not.found",username);
messages.add("login_error_1",error);
//傳遞消息
this.saveErrors(request, messages);
} catch (PasswordErrorException e) {
e.printStackTrace();
//獲取登錄成功的國際化消息
ActionMessage error = new ActionMessage("login.user.password.error");
messages.add("login_error_2",error);
//傳遞消息
this.saveErrors(request, messages);
}
return mapping.findForward("error");
}
}
~~~
? ? 來一個手動切換語言的類,方便演示:
~~~
package com.bjpowernode.struts;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
/**
* 完成語言的手動切換
* @author Longxuan
*
*/
public class ChangeLanguageAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//獲取語言
String lang = request.getParameter("lang");
String[] split = lang.split("-");
//設置語言
Locale locale = new Locale(split[0],split[1]);
this.setLocale(request, locale);
return mapping.findForward("login");
}
}
~~~
? ? 新建國際化信息文件:創建resource包,創建 英文語言包MessageBundle_en_US.properties,中文語言包MessageBundle_zh_CN.properties,默認語言包MessageBundle.properties 這3個語言包。具體內容如下:
英文語言包和默認語言包設置成一樣的:
~~~
# -- standard errors --
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 Succedd!!
login.user.not.found=Use cant be found! Username=[{0}]
login.user.password.error=Password Error!
~~~
中文語言包:
~~~
# -- standard errors --
errors.header=<UL>
errors.prefix=<font color="red"><LI>
errors.suffix=</LI></font>
errors.footer=</UL>
login.form.field.username=\u7528\u6237\u540D
login.form.field.password=\u5BC6\u7801
login.form.button.login=\u767B\u5F55
login.success={0}\uFF0C\u767B\u5F55\u6210\u529F\uFF01
login.user.not.found=\u7528\u6237\u672A\u627E\u5230\uFF0C\u7528\u6237\u540D\uFF1A\u3010{0}\u3011
login.user.password.error=\u5BC6\u7801\u9519\u8BEF
~~~
? ? 把login.jsp源碼也貼出來:
~~~
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!-- ${sessionScope['org.apache.struts.action.LOCALE']}可以獲取到當前設置的語言 -->
<fmt:setLocale value="${sessionScope['org.apache.struts.action.LOCALE']}" />
<fmt:setBundle basename="resource.MessageBundle" />
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Struts登錄</title>
</head>
<body>
<a href="changelang.do?lang=zh-cn">中文登錄</a>|
<%--<a href="changelang.do?lang=en-us">English Login</a><br>
<html:link action="changelang.do?lang=zh-cn">中文登錄</html:link>|--%>
<html:link action="changelang.do?lang=en-us">English Login</html:link>
<hr>
<html:errors />
<hr>
<h3>
struts標簽讀取國際化文件
</h3>
<form action="login.do" method="post">
<bean:message key="login.form.field.username" />
:
<input type="text" name="username" />
<br />
<bean:message key="login.form.field.password" />
:
<input type="text" name="password" />
<br />
<input type="submit"
value="<bean:message key="login.form.button.login"/>" />
</form>
<hr>
<h3>
jstl讀取國際化文件
</h3>
<form action="login.do" method="post">
<fmt:message key="login.form.field.username" />
:
<input type="text" name="username" />
<br />
<fmt:message key="login.form.field.password" />
:
<input type="text" name="password" />
<br />
<input type="submit"
value="<fmt:message key="login.form.button.login"/>" />
</form>
</body>
</html>
~~~
login_success.jsp:
~~~
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
<!-- message 屬性設置為true,則讀取message中的消息,false,則讀取error中的消息。 saveMessages/saveErrors-->
<html:messages id="msg" message="true">
<bean:write name="msg"/>
</html:messages>
</body>
</html>
~~~
? ? 最后的最后,在web.xml中配置一下struts:
~~~
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
~~~
在Struts-config.xml中配置action,actionform等信息:
~~~
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config>
<form-beans>
<form-bean name="loginForm" type="com.bjpowernode.struts.LoginActionForm"></form-bean>
</form-beans>
<action-mappings>
<action path="/login"
type="com.bjpowernode.struts.LoginAction"
name="loginForm"
scope="request" >
<forward name="success" path="/login_success.jsp"></forward>
<!--<forward name="error" path="/login_error.jsp"></forward>-->
<forward name="error" path="/login.jsp"></forward>
</action>
<action path="/changelang"
type="com.bjpowernode.struts.ChangeLanguageAction"
>
<forward name="login" path="/login.jsp" redirect="true"></forward>
</action>
</action-mappings>
<message-resources parameter="resource.MessageBundle"></message-resources>
</struts-config>
~~~
? ? 到此實例結束。點擊[這里](http://try09.tomcat.800m.net/struts_i18n_exception/)查看效果。也可以[下載源碼](http://pan.baidu.com/share/link?shareid=1174962433&uk=1259218556)。最后來2張效果圖吧。

?
- 前言
- Struts 簡單小結
- 深入淺出了解Struts的處理流程(有圖有真相)
- struts標簽+jstl標簽之國際化實例
- 一口一口吃掉Hibernate(二)——別被世俗蒙蔽了雙眼:Hibernate中Session之get和load方法的真正區別
- 一口一口吃掉Hibernate(一)——使用SchemaExport生成數據表
- 一口一口吃掉Hibernate(三)——Hibernate給表和字段設置前后綴及分隔符
- 一口一口吃掉Hibernate(四)——多對一單向關聯映射
- 一口一口吃掉Hibernate(五)——一對多單向關聯映射
- 一口一口吃掉Hibernate(六)——多對多關聯映射
- 一口一口吃掉Hibernate(七)——繼承映射
- 一口一口吃掉Hibernate(八)——Hibernate中inverse的用法
- 一覽Spring全貌
- 包辦婚姻的Spring IoC
- 3幅圖讓你了解Spring AOP
- Spring Aop實例之xml配置
- Spring Aop實例之AspectJ注解配置