struts2.0 验证框架 如何做集合验证?越详细越好1
发布网友
发布时间:2023-10-08 18:24
我来回答
共1个回答
热心网友
时间:2024-11-28 07:21
首先我们需要继承FieldValidatorSupport类,然后我们重写他的validate方法
validate
package com.opensymphony.xwork2.validator.validators;
import com.opensymphony.xwork2.validator.ValidationException;
public class ListPropertyValidator extends FieldValidatorSupport {
public void validate(Object object) throws ValidationException {
String fieldName = getFieldName();//userList[$i].username
Object value = this.getFieldValue("userList[0].username", object);//here is very important
System.out.println(value);
if ((minLength > -1) && (val.length() < minLength)) {
addFieldError(fieldName, object);
} else if ((maxLength > -1) && (val.length() > maxLength)) {
addFieldError(fieldName, object);
}
}
}
上面的过程还不完整,需要通过一种
Action code:
public class DemoAction extends ActionSupport {
private List<User> userList;
}
User code:
public class User implements Serializable {
private String username;
private String password;
private String gender;
//省略了getter, setter
}
Xml Configuration:
<?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="userList[$i].username">
<field-validator type="listproperty">//这里需要设计出一种比较优雅的配置方式来进行验证集合类的元素
<message key="devices.add.guest.guestid.required"></message>
</field-validator>
</field>
</validators>
追加默认的验证器:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator Config 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-validator-config-1.0.dtd">
<!-- START SNIPPET: validators-default -->
<validators>
<validator name="listproperty" class="com.opensymphony.xwork2.validator.validators.ListPropertyValidator"/>
</validators>
参考资料:http://everhow.blog.163.com/blog/static/3573773200911853631870/