Over a million developers have joined DZone.

Bean Validation in JAX-RS

Here's a quick overview of the JAX-RS specification, with exception handling and customizing default JAX-RS behavior.

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

I have not dug into the Bean Validation specification into detail before, but one of the entries posted in the Payara issue tracker made me explore how the JAX-RS specification integrates/leverages the Bean Validation features.

Note: Bean Validation has been around since Java EE 6, but its integration with JAX-RS was materialized only in the latest (2.0) version (part of Java EE 7) 

In case you want to jump right into the code, you can fork it from GitHub

Quick Overview

I don’t want to dive into too many details:

  • JAX-RS supports declarative (as opposed to programmatic) validation using annotations from Bean Validation specification
  • It supports application of constraints to JAX-RS resource classes, method parameters (both request bodies as well as other components such as headers and URI parts like query parameters etc.), method return types and fields as well
@Path("users")
public class UsersResource {

    @HeaderParam("token")
    @Valid
    private Token token;

    @POST
    @Produces("application/json")
    @Consumes("application/json")
    public void save(@Valid User user){
        System.out.println("saved :: " + user);
    }

    @GET
    @Path("{name}")
    @Produces("application/json")
    public @Valid User get(@PathParam("name") String name){
        return new User(name, name+"@test.com");
    }
}

The JAX-RS spec also defines default behaviour for scenarios when the bean  validation constraints are violated

Exception Handling

JAX-RS implementations are forced to provide (by the spec) a default ExceptionMapper for handling bean validation constraint violation exceptions. It returns standard responses (HTTP 400/500) to clients based on some (default) rules outlined in the specification (see section 7.6 of the JAX-RS spec doc)

Customizing Default JAX-RS Behavior

The default JAX-RS behaviour can be overridden by providing your own (custom) Exception Mapper implementation.

@Provider
public class BeanValConstrainViolationExceptionMapper implements ExceptionMapper<ConstraintViolationException>{

    @Override
    public Response toResponse(ConstraintViolationException e) {
        System.out.println("BeanValConstrainViolationExceptionMapper in action");

        ConstraintViolation cv = (ConstraintViolation) e.getConstraintViolations().toArray()[0];
        //oh yeah... you need to shell out some $$$ !
        return Response.status(Response.Status.PAYMENT_REQUIRED)
                .entity(new ConstraintViolationEntity(cv.getMessage()))
                .build();
    }

}

Further Reading

  • I would encourage you to dig into Chapter 7 of the JAX-RS 2.0 specification document for deeper insight into this topic. It’s brief and to the point
  • Oh, and here is the link to the latest Bean Validation (1.1) spec doc

Cheers!

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:
java ,jax-rs

Published at DZone with permission of Abhishek Gupta, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}