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
