JAX-RS - Performing Entity Validation by Using @Valid

[Last Updated: 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.


A JAX-RS resource

public class CustomerResource {

  public String createCustomer(@Valid Customer customer) {
      System.out.println("-- in createCustomer() method --");
      return String.format("Customer created : %s%n", customer);

The Java Bean

public class Customer {
  private String name;
  private String address;
  @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.

public class MyExceptionMapper
               implements ExceptionMapper<ConstraintViolationException> {

  public Response toResponse(final ConstraintViolationException exception) {
      return Response.status(Response.Status.BAD_REQUEST)

  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();

      Client client = ClientBuilder.newBuilder().build();
      WebTarget target =
      Response response = target.request()
                                      MediaType.TEXT_XML), Response.class);


createCustomer.arg0.phoneNumber must match "\d{3}-\d{3}-\d{4}" 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