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.

Example

A 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 ExceptionMapper

We 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 client

public 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));
  }
}

Output

createCustomer.arg0.phoneNumber must match "\d{3}-\d{3}-\d{4}"
createCustomer.arg0.name may not be null
createCustomer.arg0.address may not be null

Example Project

Dependencies and Technologies Used :

  • jersey-server 2.25.1: Jersey core server implementation.
  • jersey-container-servlet 2.25.1: Jersey core Servlet 3.x implementation.
  • jersey-bean-validation 2.25.1: Jersey extension module providing support for Bean Validation (JSR-349) API.
  • JDK 1.8
  • Maven 3.3.9

Entity Validation Example Select All Download
  • jaxrs-entity-validation
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also