Is there a way to use JSR-303 (hibernate) annotations and modify the Message using {0} {1} syntax? It seem that using a Spring Validator gets you this:
String args[] = {"mark", "is", "cool"};
ValidationUtils.rejectIfEmptyOrWhitespace(errors,开发者_Python百科 "aboutYou", "aboutYou.required", args);So I can change the message. However, if I use annotations, I cannot use the message args. I understand that there are limited (min, max, etc.) args to use, but we want to make a generic statement and add some text.
java: @NotEmpty (message="validation.name.required") private String name;
properties validation.name.required={0} is required...
Output:
Full name is required.
In your interface:
public @interface Test{
int value() default 7;
String message() default "{MESSAGE}";
}
In your messages file:
MESSAGE=Testing param {value}
Output:
Testing param 7
As found here and here, works for validators which do not use hibernate also.
As it seems you're using Spring, this might help: http://blog.inflinx.com/2010/03/10/jsr-303-bean-validation-using-spring-3/
You can also get the annotation-parameters (like min- and max- annotation-values for @Size) from ConstraintViolation< Object> -object (javax.validation.Validator.validate(Object) -method returns a Set< ConstraintViolation< Object>>) with .getConstraintDescriptor.getAttributes(), if you want to parameterize them to the messages with the {0} {1} etc. -notation (the numbers might be something else than 0 and 1 for @Size for example, I don't have the code at hand, but I seem to recall that there was some other data "in between" in the Map that getAttributes returned).
Note that in my case I used programmatic validation (getting Validator-object from Validation.buildDefaultValidatorFactory().getValidator() and using it to validate an object with JSR-303 -annotations), extracted the needed data from the Set of ConstraintViolations (if the Set was not empty), put the data in a custom Exception-class and threw it out of the service, all the way to a org.springframework.web.servlet.HandlerExceptionResolver -implementation, that would gather the localization keys and message parameters from the exception object and localize the messages via MessageSource, so this might not be exactly what you're looking for.
精彩评论