5

目前,我有类似的东西

@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.

4

1 回答 1

8

你可以这样做:

@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.
于 2015-06-24T07:39:27.563 回答