截获*.do的页面请求——调用srtuts-config.xml查找对应的*.do——找对应的表单预处理项Form Bean和核心处理项HelloAction进行处理。Form Bean是对表单的封装。提交数据时,Struts会调用request.getParameter(“”)将值取出,然后通过setter方法设置到同名的FormBean属性上。另外,Form Bean有自动转化常用数据类型的功能和对用户输入信息进行validation校验的功能。其中的常用数据类型转换意思很简单,例如属性类型是int类型,但request.getParameter(“”)获取到的是String类型,Structs会调用Integer.parseInt(“”)转化为int类型。下面我们以具体实例来演示FormBean的validation表单校验功能。
FormBean的表单校验实例:
1.页面hello.jsp:
<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<html>
<head>
<title>JSP for HelloForm form</title>
</head>
<body>
<html:form action="/hello">
姓名 : <html:text property="name"/><html:errors property="name"/><br/>
年龄 : <html:text property="age"/><html:errors property="age"/><br/>
是否用过struts?:<html:checkbox property="experience" /><br/>
<html:checkbox property="hobby" value="音乐"/>音乐
<html:checkbox property="hobby" value="体育"/>体育
<html:checkbox property="hobby" value="影视"/>影视<b><html:errors property="hobby"/></b><br/>
<html:submit/><html:cancel/>
</html:form>
</body>
</html>
2.helloForm及其validation:
public class HelloForm extends ActionForm {
private String name;
private int age;
private boolean experience;
private Date date;
private Time time;
private String[] hobby;
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
// TODO Auto-generated method stub
ActionErrors errors=new ActionErrors();
if(name==null||name.trim().length()==0)
errors.add("name",new ActionMessage("hello.error.name"));
if(hobby==null||hobby.length<1)
errors.add("hobby",new ActionMessage("hello.error.hobby"));
if(age<5)
errors.add("age",new ActionMessage("hello.error.age",5));
return errors;
}
public void reset(ActionMapping mapping, HttpServletRequest request) {
// TODO Auto-generated method stub
age=5;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isExperience() {
return experience;
}
public void setExperience(boolean experience) {
this.experience = experience;
}
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
public Time getTime() {
return time;
}
public void setTime(Time time) {
this.time = time;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
在HelloForm中我们看到用于验证的部分有姓名和喜好以及年龄,为空的话或者年龄小于5都会放到errors.add("",)里,然后在struts-config.xml里我们看到 <message-resources parameter="com.li.struts.ApplicationResources"/>,ApplicationResources是一个文件,存储着错误名和相应值的键值对。