JAX-RS - Performing Entity Validation by Using @Valid [Updated: Aug 18, 2017, Created: Aug 18, 2017] |
|
||
Request entity bodies can be mapped to resource method parameters as Java bean (explained here). Entity validation can be enabled by using @Valid with such entity parameters, given that the Java bean class is decorated with Bean Validation annotations. ExampleA JAX-RS resource@Path("/customers") public class CustomerResource { @POST public String createCustomer(@Valid Customer customer) { System.out.println("-- in createCustomer() method --"); return String.format("Customer created : %s%n", customer); } } The Java Bean@XmlRootElement public class Customer { @NotNull private String name; @NotNull private String address; @NotNull @Pattern(regexp = "\\d{3}-\\d{3}-\\d{4}") private String phoneNumber; ............. } Writing an ExceptionMapperWe are going to write an exception Mapper to return a custom validation error message. @Provider public class MyExceptionMapper implements ExceptionMapper<ConstraintViolationException> { @Override public Response toResponse(final ConstraintViolationException exception) { return Response.status(Response.Status.BAD_REQUEST) .entity(prepareMessage(exception)) .type("text/plain") .build(); } private String prepareMessage(ConstraintViolationException exception) { String msg = ""; for (ConstraintViolation<?> cv : exception.getConstraintViolations()) { msg+=cv.getPropertyPath()+" "+cv.getMessage()+"\n"; } return msg; } } To try examples, run embedded tomcat (configured in pom.xml of example project below): mvn tomcat7:run-war JAX-RS clientpublic class MyClient { public static void main(String[] args) throws Exception { Customer customer = new Customer(); customer.setName(null); customer.setAddress(null); customer.setPhoneNumber("343-343-343"); Client client = ClientBuilder.newBuilder().build(); WebTarget target = client.target("http://localhost:8080/customers"); Response response = target.request() .post(Entity.entity(customer, MediaType.TEXT_XML), Response.class); System.out.println(response.readEntity(String.class)); } } OutputcreateCustomer.arg0.phoneNumber must match "\d{3}-\d{3}-\d{4}" Example ProjectDependencies and Technologies Used:
|
|
||
|
|||
|