adam bien's blog

CDI Input Validation with JAX-RS and Java EE 8 📎

A CDI bean with parameters validated by Bean Validation:


import javax.validation.constraints.Size;
public class WorkshopCatalog {

    public void save(@Size(min = 2, max = 5) String input) {
        //...
    }
}

and exposed with a JAX-RS resource:

@Path("workshops")
public class WorkshopsResource {

    @Inject
    WorkshopCatalog facade;

    @POST
    public void save(String input) {
        this.facade.save(input);
    }
}    

throws on every violation an instance of ValidationException which is automatically converted by JAX-RS into 400 Bad Request.

An invalid request with too short payload, like e.g.:

curl -i -XPOST -d'd' http://localhost:8080/beanvalidation/resources/workshops

leads to:


HTTP/1.1 400 Bad Request
Server: Payara Server  5.184 #badassfish
(...)

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.