struts2输入校验流程:
1.类型转换器对请求参数执行类型转换,并把转换后的值赋给aciton中的属性
2.如果在执行类型转换的过程中出现异常,系统会将异常信息保存到ActionContext,
conversionError拦截器将异常信息添加到fieldErrors里,不管类型转换是否出现异常,都会进入第三步
3.系统通过反射技术先调用action的validateXXX方法
4.再调用aciton中的validate方法
5.经过上述的4步,如果系统中的fieldErrors存在错误信息,系统自动将请求转发至名称为input的视图
如果系统中的fieldErrors没有任何错误信息,系统将执行aciton中的处理方法。
也就是说转发至input视图有两个原因:1.类型转换异常
2.输入校验不合法
如下:
InvidateAction.java:
package com.itheima.action;
import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;
public class InvidateAction extends ActionSupport{
private String username;
private String tel;
private Date birthday;
private String msg;
public void setUsername(String username) {
this.username = username;
}
public void setTel(String tel) {
this.tel = tel;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getMsg() {
return msg;
}
public void validate() {
}
public String execute1() {
msg = "execute1";
return "success";
}
public String execute2() {
msg = "execute2";
return "success";
}
}
person.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
Insert title here
struts2.xml
/success.jsp /person.jsp
我在jsp中输入信息如下:

则会提示:
vcyzzLLOvPujumh0dHA6Ly9ibG9nLmNzZG4ubmV0L202MzE1MjEzODMvYXJ0aWNsZS9kZXRhaWxzLzQwNjgwNzIzPC9wPgo8cD5JbnZpZGF0ZUFjdGlvbi5qYXZhOjwvcD4KPHA+PC9wPgo8cHJlIGNsYXNzPQ=="brush:java;">package com.itheima.action; import java.util.Date; import com.opensymphony.xwork2.ActionSupport; public class InvidateAction extends ActionSupport{ private String username; private String tel; private Date birthday; private String msg; public void setUsername(String username) { this.username = username; } public void setTel(String tel) { this.tel = tel; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMsg() { return msg; } public void validate() { } public String execute1() { msg = "execute1"; return "success"; } public String execute2() { msg = "execute2"; return "success"; } }
DateTypeConverter.java:
package com.itheima.converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;
public class DateTypeConverter extends DefaultTypeConverter{
@Override
public Object convertValue(Map
context, Object value,
Class toType) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmdd");
if(toType == Date.class) {
String[] strs = (String[])value;
Date date = null;
try {
date = dateFormat.parse(strs[0]);
} catch (ParseException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return date;
} else if(toType == String.class) {
return dateFormat.format((Date)value);
}
return null;
}
}
InvidateAction-conversion.properties:
birthday=com.itheima.converter.DateTypeConverter
项目树:
