在struts2.0中,通过validator annotation的方式能不能实现如下功能?
如果可以的话,如何实现?1)首先对某一些字段进行逻辑判断
2)针对逻辑判断的结果,对相应field的数据进行验证比如:
现在有三个textfield,分别标识为:type,user,customer
如果type=1 ==> 对user进行数据验证
如果type=2 ==> 对customer进行数据验证
这三个字段属于同一个formBean里的内容,
我们项目组目前对于formBean里的数据都是在setter方法前面用annotation的方式进行数据校验
不知道可否实现上面提到的功能
import java.util.List;
import java.util.Map;import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validation;@Validation
public class Ol001JokenForm {
private String type;
private String user;
private String customer; public String getType() {
return type;
}

@RequiredStringValidator(message="",key="Ol001JokenForm.type.requiredString")
public void setType(String type) {
this.type = type;
} public String getUser() {
return user;
}

@RequiredStringValidator(message="",key="Ol001JokenForm.user.requiredString")
public void setUser(String user) {
this.user = user;
} public String getCustomer() {
return customer;
}

@RequiredStringValidator(message="",key="Ol001JokenForm.customer.requiredString")
public void setCustomer(String customer) {
this.customer = customer;
}
}

解决方案 »

  1.   

    如果楼主的目的只是为了对数据进行验证,建议先在Action中用代码解决。如果楼主的目的是为了学会这个知识点,则只能静待高手大驾光临啦。呵呵。
      

  2.   

    楼主可以使用ExpressionValidator,其可以使用ONGL表达式来进行验证。
    楼主,你按下边这样写试试:    @ExpressionValidator(expression="type == 1 ? ( user.length() > 0 ) : true",message="",key="Ol001JokenForm.user.requiredString")
        public void setUser(String user) {
            this.user = user;
        }
        
        @ExpressionValidator(expression="type == 2 ? ( customer.length() > 0 ) : true",message="",key="Ol001JokenForm.customer.requiredString")
        public void setCustomer(String customer) {
            this.customer = customer;
        }
      

  3.   

    经测试,发现使用ExpressionValidator会提示缺少fieldName属性的问题
    换成FieldExpressionValidator,顺利解决了楼主的问题!
    以下代码已经通过测试,可以成功实现楼主的验证需求。呵呵。    @FieldExpressionValidator(expression="type == 1 ? ( user.length() > 0 ) : true",message="",key="Ol001JokenForm.user.requiredString")
        public void setUser(String user) {
            this.user = user;
        }
        
        @FieldExpressionValidator(expression="type == 2 ? ( customer.length() > 0 ) : true",message="",key="Ol001JokenForm.customer.requiredString")
        public void setCustomer(String customer) {
            this.customer = customer;
        }
      

  4.   

    这个里面可以再嵌套其它类型的验证不?比如说:requiredStringValidator
    或者我们可以直接在里头写正则表达式做验证?