发表时间:2010-03-19
最后修改:2010-03-19
[size=xx-small][size=large][size=x-large][color=blue]Struts2校验框架进行数据校验
注:当用struts2校验框架对action里的对象的属性进行校验时,需要在action的包下面建一个配置文件,文件的名字是:action的名字+中划线+ validation +.xml。如: SaveUserAction-validation.xml
第一种方法:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<!-- field里的name必须和action里的属性保持一致,即user -->
<field name="user.firstname">
<field-validator type="requiredstring">
<message>请输入姓!</message>
</field-validator>
</field>
<field name="user.lastname">
<field-validator type="requiredstring">
<message>请输入名!</message>
</field-validator>
</field>
<field name="user.age">
<field-validator type="required">
<message>请输入年龄!</message>
</field-validator>
<field-validator type="int">
<param name="min">1</param>
<param name="max">150</param>
<message>年龄必须在${min}到${max}之间!</message>
</field-validator>
</field>
</validators>
第二种方法:(需要两个配置文件)
(1)一个配置文件名字如:SaveUserAction-validation.xml(放在同action一个目录下)
内容如:
<validators>
<field name="user">
<field-validator type="visitor">
<param name="context">user</param>
<param name="appendPrefix">true</param>
<message>user's</message>
</field-validator>
</field>
</validators>(两个user必须一致)
(2)另一个配置文件名字如:User-user-validation.xml(放在同bean一个目录下)
内容如:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<field name="firstname">
<field-validator type="requiredstring">
<message>请输入姓!</message>
</field-validator>
</field>
<field name="lastname">
<field-validator type="requiredstring">
<message>请输入名!</message>
</field-validator>
</field>
<field name="age">
<field-validator type="required">
<message>请输入年龄!</message>
</field-validator>
<field-validator type="int">
<param name="min">1</param>
<param name="max">150</param>
<message>年龄必须在${min}到${max}之间!</message>
</field-validator>
</field>
</validators>
(3)在action里添加validate方法:
public void validate(){
Map map = this.getFieldErrors();
Set set = map.keySet();
for(Iterator iter = (Iterator) set.iterator();iter.hasNext();){
System.out.println(map.get(iter.next()));
}
}
(4)在applicationContext.xml里的bean属性里添加prototype属性:
<bean id="saveUserAction" class="com.test.action.user.SaveUserAction" scope="prototype">
<property name="userService">
<ref bean="userService"/>
</property>
</bean>
<bean id="listUserAction" class="com.test.action.user.ListUserAction" scope="prototype">
<property name="userService">
<ref bean="userService"/>
</property>
</bean>[/size][/size][/color][/size]