Java Platform, Enterprise Edition (Java EE) 8 The Java EE Tutorial

## Validating Resource Data with Bean Validation

JAX-RS supports the Bean Validation to verify JAX-RS resource classes. This support consists of:

- Adding constraint annotations to resource method parameters

- Ensuring entity data is valid when the entity is passed in as a parameter

The following topics are addressed here:

- Using Constraint Annotations on Resource Methods

- Validating Entity Data

- Validation Exception Handling and Response Codes

### Using Constraint Annotations on Resource Methods

Bean Validation constraint annotations may be applied to parameters for a resource. The server will validate the parameters and either pass or throw a `javax.validation.ValidationException`.

    @POST
    @Path("/createUser")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public void createUser(@NotNull @FormParam("username") String username,
                           @NotNull @FormParam("firstName") String firstName,
                           @NotNull @FormParam("lastName") String lastName,
                           @Email @FormParam("email") String email) {
        ...
    }

In the preceding example, the built-in constraint `@NotNull` is applied to the `username`, `firstName`, and `lastName` form fields. Another built-in constraint `@Email` validates that the email address supplied by the `email` form field is correctly formatted.

The constraints may also be applied to fields within a resource class.

    @Path("/createUser")
    public class CreateUserResource {
      @NotNull
      @FormParam("username")
      private String username;

      @NotNull
      @FormParam("firstName")
      private String firstName;

      @NotNull
      @FormParam("lastName")
      private String lastName;

      @Email
      @FormParam("email")
      private String email;

      ...
    }

In the preceding example, the same constraints that were applied to the method parameters in the previous example are applied to the class fields. The behavior is the same in both examples.

Constraints may also be applied to a resource class’s JavaBeans properties by adding the constraint annotations to the getter method.

    @Path("/createuser")
    public class CreateUserResource {
      private String username;

      @FormParam("username")
      public void setUsername(String username) {
        this.username = username;
      }

      @NotNull
      public String getUsername() {
        return username;
      }
      ...
    }

Constraints may also be applied at the resource class level. In the following example, `@PhoneRequired` is a user-defined constraint that ensures that a user enters at least one phone number. That is, either `homePhone` or `mobilePhone` can be null, but not both.

    @Path("/createUser")
    @PhoneRequired
    public class CreateUserResource {
      @FormParam("homePhone")
      private Phone homePhone;

      @FormParam("mobilePhone")
      private Phone mobilePhone;
      ...
    }

### Validating Entity Data

Classes that contain validation constraint annotations may be used in method parameters in a resource class. To validate these entity classes, use the `@Valid` annotation on the method parameter. For example, the following class is a user-defined class containing both standard and user-defined validation constraints.

    @PhoneRequired
    public class User {
      @NotNull
      private String username;

      private Phone homePhone;

      private Phone mobilePhone;
      ...
    }

This entity class is used as a parameter to a resource method.

    @Path("/createUser")
    public class CreateUserResource {
      ...
      @POST
      @Consumers(MediaType.APPLICATION_XML)
      public void createUser(@Valid User user) {
        ...
      }
      ...
    }

The `@Valid` annotation ensures that the entity class is validated at runtime. Additional user-defined constraints can also trigger validation of an entity.

    @Path("/createUser")
    public class CreateUserResource {
      ...
      @POST
      @Consumers(MediaType.APPLICATION_XML)
      public void createUser(@ActiveUser User user) {
        ...
      }
      ...
    }

In the preceding example, the user-defined `@ActiveUser` constraint is applied to the `User` class in addition to the `@PhoneRequired` and `@NotNull` constraints defined within the entity class.

If a resource method returns an entity class, validation may be triggered by applying the `@Valid` or any other user-defined constraint annotation to the resource method.

    @Path("/getUser")
    public class GetUserResource {
      ...
      @GET
      @Path("{username}")
      @Produces(MediaType.APPLICATION_XML)
      @ActiveUser
      @Valid
      public User getUser(@PathParam("username") String username) {
        // find the User
        return user;
      }
      ...
    }

As in the previous example, the `@ActiveUser` constraint is applied to the returned entity class as well as the `@PhoneRequired` and `@NotNull` constraints defined within the entity class.

### Validation Exception Handling and Response Codes

If a `javax.validation.ValidationException` or any subclass of `ValidationException` except `ConstraintValidationException` is thrown, the JAX-RS runtime will respond to the client request with a 500 (Internal Server Error) HTTP status code.

If a `ConstraintValidationException` is thrown, the JAX-RS runtime will respond to the client with one of the following HTTP status codes:

- `500` (Internal Server Error) if the exception was thrown while validating a method return type

- `400` (Bad Request) in all other cases

Copyright © 2017, Oracle and/or its affiliates. All rights reserved.