struts1.x 国际化配置
说明:
1、在struts.cfg.xml文件中加上:
<message-resources key="backup" parameter="resource.resource" />
2、actionForm类的validate方法:
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (empname.equals("") || empname == null) {
//errors.add("empname", new ActionMessage("客户姓名不能为空",false));
errors.add("empname", new ActionMessage("item.empname.require",true));
}
Pattern pattern = Pattern.compile("^\\d+$");
//matches方法可以判断当前的字符串是否匹配给定的正则表达式。
//如果匹配,返回true,否则,返回false
Matcher matcher = pattern.matcher(age);
boolean b = matcher.matches();
if (b == false) {
//errors.add("age", new ActionMessage("年龄必须是数字",false));
errors.add("age", new ActionMessage("item.age.require"));
}
return errors;
}
或者使用参数的方式:
public ActionForward save(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//获取本地的语言类别
Locale l = request.getLocale();
System.out.println(l.toString());
EmpForm empForm=(EmpForm)form;
//age属性的值不能大于70
ActionMessages errors=new ActionMessages();
if(Integer.parseInt(empForm.getAge())>70){
//errors.add("age", new ActionMessage("您的年纪偏大",false));
Object obj[]=new Object[3];
obj[0]=empForm.getEmpname();
obj[1]=empForm.getAge();
obj[2]=70;
errors.add("age", new ActionMessage("item.age.request",obj));
if(!errors.isEmpty()){
//在requrest对象中保存错误信息
this.saveErrors(request, errors);
}
return mapping.findForward("presave");
}
return mapping.findForward("save");
}
customer.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%>
<!--
uri :注册过的标记库uri
prefix:指定匹配该标记库的标记前缀
-->
<html:html locale="true">
<head>
<title>员工界面</title>
</head>
<center>
<h1>
员工界面
</h1>
</center>
<body>
<center>
<html:form action="customerSave.do?method=save" method="post"
focus="empname">
<table border=1>
<tr>
<td>
<bean:message bundle="backup" key="item.empname"/>:
</td>
<td>
<html:text property="empname" /><html:errors property="empname"/>
</td>
</tr>
<tr>
<td>
<bean:message key="item.sex"/>:
</td>
<td>
<!-- 必须包含value属性 -->
<html:radio property="sex" value="n"></html:radio>
<bean:message bundle="backup" key="item.male"/>:
<html:radio property="sex" value="w"></html:radio>
<bean:message bundle="backup" key="item.female"/>:
</td>
</tr>
<tr>
<td>
<bean:message key="item.age"/>:
</td>
<td>
<html:text property="age"></html:text><html:errors property="age"/>
</td>
</tr>
<tr>
<td>
<bean:message key="item.tel"/>:
</td>
<td>
<html:text property="tel" />
</td>
</tr>
<tr>
<td>
<html:submit>保存</html:submit>
</td>
<td>
<html:reset value="重置"></html:reset>
</td>
</tr>
</table>
</html:form>
</center>
</body>
</html:html>