struts2.0 验证框架 如何做集合验证?越详细越好

2024-12-14 08:37:00
推荐回答(1个)
回答1:

首先我们需要继承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 userList;
}

User code:
public class User implements Serializable {
private String username;
private String password;
private String gender;
//省略了getter, setter
}

Xml Configuration:

"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">


//这里需要设计出一种比较优雅的配置方式来进行验证集合类的元素





追加默认的验证器:

"-//OpenSymphony Group//XWork Validator Config 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-validator-config-1.0.dtd">