struts2中的数据校验
一. ActionSupport是个工具类,他实现了Action, Validatable等接口, Validatable提供validate()方法进行数据验证.Action只要继承ActionSupport类,重写validate()方法就可以进行数据验证
二. 校验的流程
首先,Struts框架对输入数据进行类型转换,然后再进行数据校验,如果类型转换与数据校验都没有错误发生, 就进入execute(),否则请求将被转发到input视图
三. 注册实例
首先新建RegistAcion.java
import java.util.Calendar;
import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction extends ActionSupport {
private String username;
private String password;
private String repassword;
private int age;
private Date brithday;
private Date graduation;
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;
}
public String getRepassword() {
return repassword;
}
public void setRepassword(String repassword) {
this.repassword = repassword;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBrithday() {
return brithday;
}
public void setBrithday(Date brithday) {
this.brithday = brithday;
}
public Date getGraduation() {
return graduation;
}
public void setGraduation(Date graduation) {
this.graduation = graduation;
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
@Override
public void validate() {
if(null == username || username.length()<6 || username.length()>12){
this.addFieldError("username", "username invalid");
}
if(null == password || password.length()<6 || password.length()>10 ){
this.addFieldError("password", "password invalid");
}else
if(null == repassword || repassword.length()<6 || repassword.length()>10 ){
this.addFieldError("repassword", "re-password invalid");
}else
if(!password.equals(repassword)){
this.addFieldError("password", "two pass not same");
}
if(age<1 || age>150){
this.addFieldError("age", "age invalid");
}
if(null == brithday){
this.addFieldError("birthday", "birthday invalid");
}
if(null == graduation){
this.addFieldError("graduation", "graduation invalid");
}
if(null != brithday && null!=graduation){
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(brithday);
c2.setTime(graduation);
if(!c1.before(c2)){
this.addFieldError("birthday", "birthday should before graduation");
}
}
}
}
接着是注册页面和注册成功页面
注册页面:register.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page isELIgnored = "false"%>
<%
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 'register.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>
<table align="center" width="40%" >
<tr>
<td>
<s:fielderror></s:fielderror>
</td>
</tr>
</table>
<s:form action="register">
<table align="center" width="40%" border="1">
<tr>
<td>
username
</td>
<td>
<input type="text" name="username" value="${requestScope.username}">
</td>
</tr>
<tr>
<td>
password
</td>
<td>
<input type="password" name="password">
</td>
</tr>
<tr>
<td>
re-password
</td>
<td>
<input type="password" name="repassword">
</td>
</tr>
<tr>
<td>
age
</td>
<td>
<input type="text" name="age" value="${requestScope.age}">
</td>
</tr>
<tr>
<td>
birthday
</td>
<td>
<input type="text" name="brithday">
</td>
</tr>
<tr>
<td>
graduation
</td>
<td>
<input type="text" name="graduation">
</td>
</tr>
<tr>
<td>
<input type="submit" value=" submit ">
</td>
<td>
<input type="reset" value=" reset ">
</td>
</tr>
</table>
</s:form>
</body>
</html>
注册成功页面:success.jsp
<%@ page isELIgnored = "false"%>
<%
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 'success.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>
<table align="center" width="40%" border="1">
<tr>
<td>
username
</td>
<td>
${requestScope.username}
</td>
</tr>
<tr>
<td>
password
</td>
<td>
${requestScope.password}
</td>
</tr>
<tr>
<td>
age
</td>
<td>
${requestScope.age}
</td>
</tr>
<tr>
<td>
birthday
</td>
<td>
${requestScope.brithday}
</td>
</tr>
<tr>
<td>
graduation
</td>
<td>
${requestScope.graduation}
</td>
</tr>
</table>
</body>
</html>
配置Action
<result>/success.jsp</result>
<result name="input">/register.jsp</result>
</action>
username password 都有长度限制 不满足则会提示错误 类似:username invalid
如果 age输入为abc,会提示
Invalid field value for field "age".
1. 其中Invalid field value for field "age" 信息是struts2通过内置的类型转换器进行类型转换时,如果不能成功转换, struts2框架自动生成一条错误信息,并将该错误信息放到addFieldError里面,这种默认的输出信息格式是在 xwork-2.0.4.jar中定义的. com/opensymphony/xwork2/xwork-messages.properties文件中有一条xwork.default.invalid.fieldvalue=Invalid field value for field "{0}".
2. 这是一种全局的错误提示方式,整个系统中只要是字段类型转换错误都会这样提示,我们也可以改变这种输出格式,只要在全局的国际资源文件中重写xwork.default.invalid.fieldvalue就可以了.
实现方式:
在struts.xml中加入<constant name="struts.custom.i18n.resources" value="messageResource"></constant>
或者也可以在struts.properties中加入struts.custom.i18n.resources=messageResource
指定国际化资源文件名为messageResource. properties
新建messageResource. properties资源文件并添加数据xwork.default.invalid.fieldvalue={0} failure
修改之后字段类型转换错误提示为 : {0} failure
3 所有的类型转换失败后,struts2会将基本类型设置为0,对象类型设置为null,这里的age的类型为Integer,当类型转换失败age值为null,如果age的类型为int,那么转换失败后值为0
4.这种提示信息不够友好,也可以定义局布的提示信息,为每一个Action新建一个properties文件,文件名为XXX.properties(Action名.properties)
实现方式:新建RegistAction.properties并添加
invalid.fieldvalue.age=age error #age 类型转换错误时显示 age error
四.
Struts2也提供类似BaseDispatchAction的功能
import com.opensymphony.xwork2.ActionSupport;
public class Regist2Action extends ActionSupport {
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String regist() throws Exception {
System.out.println("注册成功-regist");
return SUCCESS;
}
public void validateRegist() {
if(userName.equals("")){
addFieldError("userName", "请输入用户名-registValidate");
}
}
}
<result name="success">/welcome.jsp</result>
<result name="input">/regist2.jsp</result>
</action>
指定了method为regist,当请求时会执行regist(),不会再去执行默认的execute()方法了,
validateRegist()方法是专门针对regist校验的.(格式为validate+方法名)