论坛首页 入门技术论坛

关于struts2验证框架中的fieldexpression验证,非常灵活。

浏览 2554 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-06-19  

例如判断输入的密码和重复输入的密码是否相同:

<field-validator type="fieldexpression">
            <param name="expression">
                (user.confirmPassword.equals(user.password))
            </param>

</field-validator>

 

fieldexpression方法的源代码在
com.opensymphony.xwork2.validator.validators.FieldExpressionValidator.class

 

public class FieldExpressionValidator extends FieldValidatorSupport {

    private String expression;


    public void setExpression(String expression) {
        this.expression = expression;
    }

    public String getExpression() {
        return expression;
    }

    public void validate(Object object) throws ValidationException {
        String fieldName = getFieldName();

        Boolean answer = Boolean.FALSE;
        Object obj = null;

        try {
            obj = getFieldValue(expression, object);
        } catch (ValidationException e) {
            throw e;
        } catch (Exception e) {
            // let this pass, but it will be logged right below
        }

        if ((obj != null) && (obj instanceof Boolean)) {
            answer = (Boolean) obj;
        } else {
            log.warn("Got result of " + obj + " when trying to get Boolean.");
        }

        if (!answer.booleanValue()) {
            addFieldError(fieldName, object);
        }
    }
}

 可以看出参数expression是一段代码的字符串,然后判断返回值boolean,true的话通过验证,否则不通过。

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics