Struts提供了国际化的功能对于一个面向各国的系统来说是非常有帮助的只需要提供每个国家的语言资源包配置后即可使用
下面来用一个登录实例来演示一下Struts的国际化配置和显示
创建一个login_in_exception的javaweb项目引入Struts的所有jar包以及jstljar和standardjar登录界面无非就是输入用户名密码所以ActionForm中只需要设置个属性即可
[java]
package combjpowernodestruts;
import orgapachestrutsactionActionForm;
/**
* 登录ActionForm负责收集表单数据
* 表单的数据必须和ActionForm的getset一致
* @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) {
thisusername = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
thispassword = password;
}
}
登录时会验证密码是否正确需要提供异常处理本实例显示个异常用户名未找到密码错误
[java]
package combjpowernodestruts;
/**
* 密码错误异常
* @author Longxuan
*
*/
@SuppressWarnings(serial)
public class PasswordErrorException extends RuntimeException {
public PasswordErrorException() {
// TODO Autogenerated constructor stub
}
public PasswordErrorException(String message) {
super(message)
// TODO Autogenerated constructor stub
}
public PasswordErrorException(Throwable cause) {
super(cause)
// TODO Autogenerated constructor stub
}
public PasswordErrorException(String message Throwable cause) {
super(message cause)
// TODO Autogenerated constructor stub
}
public PasswordErrorException(String message Throwable cause
boolean enableSuppression boolean writableStackTrace) {
super(message cause enableSuppression writableStackTrace)
// TODO Autogenerated constructor stub
}
}
package combjpowernodestruts;
/**
* 用户未找到异常
* @author Longxuan
*
*/
@SuppressWarnings(serial)
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException() {
// TODO Autogenerated constructor stub
}
public UserNotFoundException(String message) {
super(message)
// TODO Autogenerated constructor stub
}
public UserNotFoundException(Throwable cause) {
super(cause)
// TODO Autogenerated constructor stub
}
public UserNotFoundException(String message Throwable cause) {
super(message cause)
// TODO Autogenerated constructor stub
}
public UserNotFoundException(String message Throwable cause
boolean enableSuppression boolean writableStackTrace) {
super(message cause enableSuppression writableStackTrace)
// TODO Autogenerated constructor stub
}
}
提供用户管理类处理用户的相关操作这里主要处理用户登录
[java]
package combjpowernodestruts;
/**
* 用户管理类
* @author Longxuan
*
*/
public class UserManager {
/**
* 简单处理登录逻辑
* @param username 用户名
* @param password 密码
*/
public void login(String usernameString password){
if(!adminequals(username)){
throw new UserNotFoundException()
}
if(! adminequals(password)){
throw new PasswordErrorException()
}
}
}
现在写LoginAction的处理
[java]
package combjpowernodestruts;
import javaxservlethttpHttpServletRequest;
import javaxservlethttpHttpServletResponse;
import orgapachestrutsactionAction;
import orgapachestrutsactionActionForm;
import orgapachestrutsactionActionForward;
import orgapachestrutsactionActionMapping;
import orgapachestrutsactionActionMessage;
import orgapachestrutsactionActionMessages;
/**
* 登录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 = lafgetUsername()
String password = lafgetPassword()
UserManager userManager = new UserManager()
ActionMessages messages = new ActionMessages()
try {
//用户登录
userManagerlogin(username password)
//获取登录成功的国际化消息
ActionMessage success= new ActionMessage(loginsuccessusername)
messagesadd(login_success_success)
//传递消息
thissaveMessages(request messages)
return mappingfindForward(success)
} catch (UserNotFoundException e) {
eprintStackTrace()
//获取登录成功的国际化消息
ActionMessage error = new ActionMessage(loginusernotfoundusername)
messagesadd(login_error_error)
//传递消息
thissaveErrors(request messages)
} catch (PasswordErrorException e) {
eprintStackTrace()
//获取登录成功的国际化消息
ActionMessage error = new ActionMessage(loginuserpassworderror)
messagesadd(login_error_error)
//传递消息
thissaveErrors(request messages)
}
return mappingfindForward(error)
}
}
来一个手动切换语言的类方便演示
[java]
package combjpowernodestruts;
import javautilLocale;
import javaxservlethttpHttpServletRequest;
import javaxservlethttpHttpServletResponse;
import orgapachestrutsactionAction;
import orgapachestrutsactionActionForm;
import orgapachestrutsactionActionForward;
import orgapachestrutsactionActionMapping;
/**
* 完成语言的手动切换
* @author Longxuan
*
*/
public class ChangeLanguageAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping ActionForm form
HttpServletRequest request HttpServletResponse response)
throws Exception {
//获取语言
String lang = requestgetParameter(lang)
String[] split = langsplit()
//设置语言
Locale locale = new Locale(split[]split[])
thissetLocale(request locale)
return mappingfindForward(login)
}
}
新建国际化信息文件创建resource包创建 英文语言包MessageBundle_en_USproperties中文语言包MessageBundle_zh_CNproperties默认语言包MessageBundleproperties 这个语言包具体内容如下
英文语言包和默认语言包设置成一样的
[java]
# standard errors
errorsheader=<UL>
errorsprefix=<font color=red><LI>
errorssuffix=</LI></font>
errorsfooter=</UL>
loginformfieldusername=User Name
loginformfieldpassword=Password
loginformbuttonlogin=Login
loginsuccess={}Login Succedd!!
loginusernotfound=Use cant be found! Username=[{}]
loginuserpassworderror=Password Error!
中文语言包
[java]
# standard errors
errorsheader=<UL>
errorsprefix=<font color=red><LI>
errorssuffix=</LI></font>
errorsfooter=</UL>
loginformfieldusername=\u\u\uD
loginformfieldpassword=\uBC\u
loginformbuttonlogin=\uB\uF
loginsuccess={}\uFFC\uB\uF\u\uF\uFF
loginusernotfound=\u\u\uA\uE\u\uFFC\u\u\uD\uFFA\u{}\u
loginuserpassworderror=\uBC\u\u\uBEF
把loginjsp源码也贴出来
[html]
<%@ page language=java contentType=text/html; charset=GB
pageEncoding=GB%>
<%@ taglib uri=/tagsbean prefix=bean%>
<%@ taglib uri=/tagshtml prefix=html%>
<%@ taglib uri=/jsp/jstl/fmt prefix=fmt%>
<! ${sessionScope[orgapachestrutsactionLOCALE]}可以获取到当前设置的语言 >
<fmt:setLocale value=${sessionScope[orgapachestrutsactionLOCALE]} />
<fmt:setBundle basename=resourceMessageBundle />
<html>
<head>
<meta httpequiv=ContentType content=text/html; charset=GB>
<title>Struts登录</title>
</head>
<body>
<a >中文登录</a>|
<%<a >English Login</a><br>
<html:link action=changelangdo?lang=zhcn>中文登录</html:link>|%>
<html:link action=changelangdo?lang=enus>English Login</html:link>
<hr>
<html:errors />
<hr>
<h>
struts标签读取国际化文件
</h>
<form action=logindo method=post>
<bean:message key=loginformfieldusername />
:
<input type=text name=username />
<br />
<bean:message key=loginformfieldpassword />
:
<input type=text name=password />
<br />
<input type=submit
value=<bean:message key=loginformbuttonlogin/> />
</form>
<hr>
<h>
jstl读取国际化文件
</h>
<form action=logindo method=post>
<fmt:message key=loginformfieldusername />
:
<input type=text name=username />
<br />
<fmt:message key=loginformfieldpassword />
:
<input type=text name=password />
<br />
<input type=submit
value=<fmt:message key=loginformbuttonlogin/> />
</form>
</body>
</html>
login_successjsp:
[html]
<%@ page language=java contentType=text/html; charset=GB
pageEncoding=GB%>
<%@ taglib uri=/tagshtml prefix=html %>
<%@ taglib uri=/tagsbean prefix=bean %>
<!DOCTYPE html PUBLIC //WC//DTD HTML Transitional//EN /TR/html/loosedtd>
<html>
<head>
<meta httpequiv=ContentType content=text/html; charset=GB>
<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>
最后的最后在webxml中配置一下struts:
[html]
<?xml version= encoding=UTF?>
<webapp version=
xmlns=/xml/ns/jee
xmlns:xsi=//XMLSchemainstance
xsi:schemaLocation=/xml/ns/jee
/xml/ns/jee/webapp__xsd>
<welcomefilelist>
<welcomefile>loginjsp</welcomefile>
</welcomefilelist>
<servlet>
<servletname>action</servletname>
<servletclass>orgapachestrutsactionActionServlet</servletclass>
<initparam>
<paramname>config</paramname>
<paramvalue>/WEBINF/strutsconfigxml</paramvalue>
</initparam>
<initparam>
<paramname>debug</paramname>
<paramvalue></paramvalue>
</initparam>
<initparam>
<paramname>detail</paramname>
<paramvalue></paramvalue>
</initparam>
<loadonstartup></loadonstartup>
</servlet>
<! Standard Action Servlet Mapping >
<servletmapping>
<servletname>action</servletname>
<urlpattern>*do</urlpattern>
</servletmapping>
</webapp>
在Strutsconfigxml中配置actionactionform等信息
[html]
<?xml version= encoding=ISO ?>
<!DOCTYPE strutsconfig PUBLIC
//Apache Software Foundation//DTD Struts Configuration //EN
/struts/dtds/strutsconfig__dtd>
<strutsconfig>
<formbeans>
<formbean name=loginForm type=combjpowernodestrutsLoginActionForm></formbean>
</formbeans>
<actionmappings>
<action path=/login
type=combjpowernodestrutsLoginAction
name=loginForm
scope=request >
<forward name=success path=/login_successjsp></forward>
<!<forward name=error path=/login_errorjsp></forward>>
<forward name=error path=/loginjsp></forward>
</action>
<action path=/changelang
type=combjpowernodestrutsChangeLanguageAction
>
<forward name=login path=/loginjsp redirect=true></forward>
</action>
</actionmappings>
<messageresources parameter=resourceMessageBundle></messageresources>
</strutsconfig>