关于struts2验证框架中的fieldexpression验证,非常灵活。
例如判断输入的密码和重复输入的密码是否相同:
<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的话通过验证,否则不通过。