`
xxp3369
  • 浏览: 148014 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

struts国际化

阅读更多
1、struts国际化的配置
* 在struts-config.xml文件中加入:<message-resources parameter="MessageResources" />

2、提供不同版本的国际化资源文件,中文需要采用native2ascii转换成unicode

3、在jsp中采用<bean:message>标签来读取国际化消息文本

4、了解利用struts默认将locale放到session中的特性,完成采用编程的方式切换语言设置
* 参见:ChangeLanguageAction.java

5、消息文本的国际化处理,共有三个步骤:
* 创建国际化消息
* 传递国际化消息
* 显示国际化消息

如何创建国际化消息?
理解ActionMessage和ActionMessages两个对象的区别

如何传递国际化消息?
* 调用saveMessage()传递普通消息,调用saveErrors传递错误消息

如何显示国际化消息?
通过<html:messages>标签显示消息(可以显示普通消息和错误消息)
通过<html:errors>显示消息(只能显示错误消息)

LoginAction.java


package com.bjsxt.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 Administrator
 *
 */
public class LoginAction extends Action {
 
	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();

		ActionMessages messages = new ActionMessages();
		try {
			UserManager.getInstance().login(username, password);
			
			//创建国际化消息文本
			ActionMessage message = new ActionMessage("user.login.success", username);
			//ActionMessage message = new ActionMessage("user.login.success", new Object[]{username});
			messages.add("loginSuccess1", message);

			ActionMessage message1 = new ActionMessage("user.login.success", username);
			messages.add("loginSuccess2", message1);
			
			//传递国际化消息文本
			this.saveMessages(request, messages);
			return mapping.findForward("success");
		}catch(UserNotFoundException unfe) {
			unfe.printStackTrace();
			
			//创建国际化消息文本
			ActionMessage message = new ActionMessage("user.not.found", username);
			messages.add("error1", message);
			
			//传递国际化消息文本
			this.saveErrors(request, messages);
		}catch(PasswordErrorException pee) {
			pee.printStackTrace();
			//创建国际化消息文本
			ActionMessage message = new ActionMessage("user.password.error");
			messages.add("error2", message);
			
			//传递国际化消息文本
			this.saveErrors(request, messages);
		}
		return mapping.findForward("error");
	}

}
	


LoginActionForm.java


package com.bjsxt.struts;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

/**
 * 登录的ActionForm,ActionForam是做数据收集的,
 * 
 * ActionForm中的属性必须和表单中输入域的名称一致
 * @author Administrator
 *
 */
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;
	}
	
	@Override
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		System.out.println("----------LoginActionForm.reset()-----------");
	}

	@Override
	public ActionErrors validate(ActionMapping mapping,
			HttpServletRequest request) {
		System.out.println("----------LoginActionForm.validate()-----------");
		return null;
	}
	
}


UserManager.java


package com.bjsxt.struts;

public class UserManager {

	private static UserManager instance = new UserManager();
	
	private UserManager() {}
	
	public static UserManager getInstance() {
		return instance;
	}
	
	public void login(String username, String password) {
		if (!"admin".equals(username)) {
			throw new UserNotFoundException();
		}
		if (!"admin".equals(password)) {
			throw new PasswordErrorException();
		}
	}
	
}


ChangeLanguageAction.java


package com.bjsxt.struts;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.Globals;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

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 currentLocale = Locale.getDefault(); 
		if ("zh".equals(lang)) {
			currentLocale = new Locale("zh", "CN");
		}else if("en".equals(lang)) {
			currentLocale = new Locale("en", "US");
		}
		//request.getSession().setAttribute(Globals.LOCALE_KEY, currentLocale);
		
		this.setLocale(request, currentLocale);
		return mapping.findForward("index");
	}

}


UserNotFoundException.java

package com.bjsxt.struts;

public class UserNotFoundException extends RuntimeException {

}



PasswordErrorException.java


package com.bjsxt.struts;

public class PasswordErrorException extends RuntimeException {

}



MessageResources.properties

引用
# -- standard errors --
errors.header=<UL>
errors.prefix=<LI><font color="red">
errors.suffix=</font></LI>
errors.footer=</UL>


user.title=User Login
user.username=User Name
user.password=Password
user.button.login=Login

user.login.success={0},Login Success
user.not.found=User Not Found,UserName[{0}]
user.password.error=Password Error
user.login.error=Login Error




MessageResources_en_US.properties


引用
# -- standard errors --
errors.header=<UL>
errors.prefix=<LI><font color="red">
errors.suffix=</font></LI>
errors.footer=</UL>

user.title=User Login
user.username=User Name
user.password=Password
user.button.login=Login

user.login.success={0},Login Success
user.not.found=User Not Found,UserName[{0}]
user.password.error=Password Error
user.login.error=Login Error



MessageResources_zh_CN.properties


引用
# -- standard errors --
errors.header=<UL>
errors.prefix=<LI><font color="red">
errors.suffix=</font></LI>
errors.footer=</UL>

user.title=\u7528\u6237\u767b\u5f55
user.username=\u7528\u6237
user.password=\u5bc6\u7801
user.button.login=\u767b\u5f55

user.login.success={0},\u767b\u5f55\u6210\u529f
user.not.found=\u7528\u6237\u4e0d\u80fd\u627e\u5230\uff0c\u7528\u6237\u540d\u79f0=[{0}]
user.password.error=\u5bc6\u7801\u9519\u8bef
user.login.error=\u767b\u5f55\u5931\u8d25


struts-config.xml


<?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.bjsxt.struts.LoginActionForm"/>
	</form-beans>
	
	<action-mappings>
		<action path="/login"
				type="com.bjsxt.struts.LoginAction"
				name="loginForm"
				scope="request"
				validate="false"
		>
			<forward name="success" path="/login_success.jsp"/>
			<forward name="error" path="/login.jsp"/>
		</action>
		
		<action path="/changelang"
				type="com.bjsxt.struts.ChangeLanguageAction"
		>
			<forward name="index" path="/index.jsp"/>
		</action>
	</action-mappings>
	
	<message-resources parameter="res.MessageResources" />
</struts-config>



index.jsp


<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
    <a href="login.jsp">登录</a><br>
    <a href="changelang.do?lang=zh">中文</a>&nbsp&nbsp&nbsp<a href="changelang.do?lang=en">英文</a>
    <p>
    <a href="login_jstl.jsp">登录(jstl国际化)</a>
  </body>
</html>



login_jstl.jsp


<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<fmt:setLocale value="${header['accept-language']}"/>
<fmt:setBundle basename="res.MessageResources"/>
<html>
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title><fmt:message key="user.title"/></title>
</head>
<body>
	<h1><fmt:message key="user.title"/></h1>
	<hr>
	<form action="login.do" method="post">
		<fmt:message key="user.username"/>:<input type="text" name="username"><br>
		<fmt:message key="user.password"/>:<input type="password" name="password"><br>
		<input type="submit" value="<fmt:message key="user.button.login"/>">
	</form>
</body>
</html>


login.jsp


<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@ taglib prefix="bean" uri="http://struts.apache.org/tags-bean"%>  
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>  
<!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><bean:message key="user.title"/></title>
</head>
<body>
	<h1><bean:message key="user.title"/></h1>
	<hr>
	<!-- 
	<font color="red">
		<html:messages id="msg" property="error1">
			<bean:write name="msg"/>
		</html:messages>
	</font>	
	<font color="blue">
		<html:messages id="msg" property="error2">
			<bean:write name="msg"/>
		</html:messages>
	</font>	
	 -->
	 <html:errors/>
	<form action="login.do" method="post">
		<bean:message key="user.username"/>:<input type="text" name="username"><br>
		<bean:message key="user.password"/>:<input type="password" name="password"><br>
		<input type="submit" value="<bean:message key="user.button.login"/>">
	</form>
</body>
</html>


login_error.jsp


<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@ taglib prefix="bean" uri="http://struts.apache.org/tags-bean"%>
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>       
   
<!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></title>
</head>
<body>
	<font color="red">
	<li>
		<html:messages id="msg" property="error1">
			<bean:write name="msg"/>
		</html:messages>
	</li>
	</font>	
	<font color="blue">
	<li>
		<html:messages id="msg" property="error2">
			<bean:write name="msg"/>
		</html:messages>
	</li>	
	</font>	
	
</body>
</html>


login_success.jsp

<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<%@ taglib prefix="bean" uri="http://struts.apache.org/tags-bean"%>
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>       
<!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></title>
</head>
<body>
	<html:messages id="msg" message="true" property="loginSuccess1">
		<bean:write name="msg"/>
	</html:messages>
</body>
</html>
分享到:
评论
1 楼 sunloveny 2009-09-29  

相关推荐

Global site tag (gtag.js) - Google Analytics