如何通过Java Validator消息传递参数?

时间:2015-06-24 07:12:19

标签: java spring java-ee spring-validator

目前,我有类似

的内容
@NotNull(message="{err.required}")
@Size(min=1, message="{err.required}")
private String firstName;

在我的messages.properties中,我有

err.required={0} is required.

它有效,但它打印出firstName is required.,这很难看。它将变量名称firstName作为{0}中的参数传递。

如何传递类似" 名字"代替?因此它将成为First name is required.

1 个答案:

答案 0 :(得分:3)

你可以这样做:

@NotNull(message="First name {err.required}")
@Size(min=1, message="First name {err.required}")
private String firstName;

@NotNull(message="Last name {err.required}")
@Size(min=1, message="Last name {err.required}")
private String lastName;

并在属性文件中

err.required= is required. 

或者如果您想更清楚,可以添加自己的注释和验证器:

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { NotEmptyValidator.class })
public @interface NotEmpty {

    String message() default "{customMessage} is required.";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };

    String customMessage() default "";
}

public class NotEmptyValidator implements ConstraintValidator<NotEmpty, String>
{
    @Override
    public void initialize(NotEmpty notEmpty)
    {        
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context)
    {
        return value != null && !value.isEmpty();
    }
}

然后你的领域

@NotEmpty(message="{err.required}"
          customMessage="First name")
private String firstName;

并且在属性中(虽然它不是必需的,因为您可以将值默认为此):

err.required={customMessage} is required.