【发布时间】:2011-08-09 10:44:59
【问题描述】:
我编写了一个 JSR303 验证器,用于将属性值与约束进行比较:
@Documented
@Constraint(validatedBy = Cmp.LongCmpValidator.class)
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
public @interface Cmp {
String message() default "{home.lang.validator.Cmp.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
long value();
public enum REL { LT,LT_EQ,EQ,GT,GT_EQ;
@Override
public String toString() {
return toString_property();
}
public String toString_property() {
switch(this) {
case LT : return "{home.lang.validator.Cmp.REL.LT}";
case LT_EQ: return "{home.lang.validator.Cmp.REL.LT_EQ}";
case EQ: return "{home.lang.validator.Cmp.REL.EQ}";
case GT : return "{home.lang.validator.Cmp.REL.GT}";
case GT_EQ: return "{home.lang.validator.Cmp.REL.GT_EQ}";
}
throw new UnsupportedOperationException();
}
public String toString_common() { return super.toString(); }
public String toString_math() { switch(this) {
case LT : return "<";
case LT_EQ: return "\u2264";
case EQ: return "=";
case GT : return ">";
case GT_EQ: return "\u2265";
}
throw new UnsupportedOperationException();
}
}
REL prop_rel_cnstr();
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@interface List {
Cmp[] value();
}
class LongCmpValidator implements ConstraintValidator<Cmp, Number> {
long cnstr_val;
REL prop_rel_cnstr;
public void initialize(Cmp constraintAnnotation) {
cnstr_val = constraintAnnotation.value();
prop_rel_cnstr = constraintAnnotation.prop_rel_cnstr();
}
public boolean isValid(Number _value, ConstraintValidatorContext context) {
if(_value == null) return true;
if(_value instanceof Integer) {
int value = _value.intValue();
switch(prop_rel_cnstr) {
case LT : return value < cnstr_val;
case LT_EQ: return value <= cnstr_val;
case EQ: return value == cnstr_val;
case GT : return value > cnstr_val;
case GT_EQ: return value >= cnstr_val;
}
}
// ... handle other types
return true;
}
}
}
ValidationMessages.properties:
home.lang.validator.Cmp.REL.LT=less than
home.lang.validator.Cmp.REL.LT_EQ=less than or equal
home.lang.validator.Cmp.REL.EQ=equal
home.lang.validator.Cmp.REL.GT=greater
home.lang.validator.Cmp.REL.GT_EQ=greater than or equal
home.lang.validator.Cmp.message=Failure: validated value is to be in relation "{prop_rel_cnstr}" to {value}.
工作正常。几乎。我收到的验证消息如下所示:
Failure: validated value is to be in relation "{home.lang.validator.Cmp.REL.GT}" to 0.
有人可以建议简单方便的方法,如何让验证器识别和解析嵌套的 {home.lang.validator.Cmp.REL.GT} 键?我需要它在处理验证的 JSF2 中很好用。 我没有使用 Spring,而是使用 hibernate-validator 4。
顺便说一句,hibernate-validator 4 似乎没有完全实现 JSR303,因为在 4.3.1.1 中的后期状态。:
- 消息参数提取自 消息字符串并用作键 搜索名为的 ResourceBundle ValidationMessages(通常物化 作为属性文件 /ValidationMessages.properties 及其 语言环境变体)使用定义的 语言环境(见下文)。如果一个属性是 找到了,message参数是 替换为中的属性值 消息字符串。 已应用第 1 步 递归直到没有替换 执行(即消息参数 value 本身可以包含一条消息 参数)。
【问题讨论】:
标签: jsf-2 validation resourcebundle hibernate-validator bean-validation