@GET
@Path("{id}")
public Person getPerson(@PathParam("id")@Pattern(regexp = "[0-9]+", message = "The id must be a valid number")String id) {return persons.get(id);
}
person.id.notnull=The person id must not be null
person.id.pattern=The person id must be a valid number
person.name.size=The person name must be between {min} and {max} chars long
注意: {min}和{max}是指與消息相關聯的約束的屬性。
一旦定義,這些消息就可以注入到驗證約束中,例如:
@POST
@Path("create")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response createPerson(@FormParam("id")@NotNull(message = "{person.id.notnull}")@Pattern(regexp = "[0-9]+", message = "{person.id.pattern}")String id,@FormParam("name")@Size(min = 2, max = 50, message = "{person.name.size}")String name) {Person person = new Person();person.setId(Integer.valueOf(id));person.setName(name);persons.put(id, person);return Response.status(Response.Status.CREATED).entity(person).build();
}
/*** {@link ThreadLocal} to store the Locale to be used in the message interpolator.*/
public class LocaleThreadLocal {public static final ThreadLocal<Locale> THREAD_LOCAL = new ThreadLocal<Locale>();public static Locale get() {return (THREAD_LOCAL.get() == null) ? Locale.getDefault() : THREAD_LOCAL.get();}public static void set(Locale locale) {THREAD_LOCAL.set(locale);}public static void unset() {THREAD_LOCAL.remove();}
}
/*** Custom configuration of validation. This configuration can define custom:* <ul>* <li>MessageInterpolator - interpolates a given constraint violation message.</li>* <li>TraversableResolver - determines if a property can be accessed by the Bean Validation provider.</li>* <li>ConstraintValidatorFactory - instantiates a ConstraintValidator instance based off its class.* <li>ParameterNameProvider - provides names for method and constructor parameters.</li> ** </ul>*/
@Provider
public class ValidationConfigurationContextResolver implements ContextResolver<GeneralValidator> {/*** Get a context of type {@code GeneralValidator} that is applicable to the supplied type.** @param type the class of object for which a context is desired* @return a context for the supplied type or {@code null} if a context for the supplied type is not available from* this provider.*/@Overridepublic GeneralValidator getContext(Class<?> type) {Configuration<?> config = Validation.byDefaultProvider().configure();BootstrapConfiguration bootstrapConfiguration = config.getBootstrapConfiguration();config.messageInterpolator(new LocaleSpecificMessageInterpolator(Validation.byDefaultProvider().configure().getDefaultMessageInterpolator()));return new GeneralValidatorImpl(config.buildValidatorFactory(),bootstrapConfiguration.isExecutableValidationEnabled(),bootstrapConfiguration.getDefaultValidatedExecutableTypes());}
}
{"exception": null,"fieldViolations": [],"propertyViolations": [],"classViolations": [],"parameterViolations": [{"constraintType": "PARAMETER","path": "getPerson.id","message": "The id must be a valid number","value": "test"}],"returnValueViolations": []
}
當前無法在Eclipse上使用選項Run As >> JUnit Test ,因為必須存在名為jbossHome的系統屬性。 Eclipse不會從Surefire / Failsafe配置中讀取此屬性。 有沒有解決方法?
當使用RESTEasy的ExceptionMapper<ValidationException>默認實現時,以application/xml媒體類型請求數據并發生驗證錯誤,將引發以下異常: org.jboss.resteasy.core.NoMessageBodyWriterFoundFailure:Could not find MessageBodyWriter for response object of type:org.jboss.resteasy.api.validation.ViolationReport of media type:application/xml