Custom input validation with JAX-RS and JSON-B (Java EE 8)

The state of a POJO (Plain Old JSON Object :-) can be validated after retrieval:

public class Developer {

    public String language;
    public int age;
    //optional field
    public String description;

    public void validate() {
        if (!language.endsWith("va") && age < 200) {
            throw new WebApplicationException(Response.
                    header("reason", "Learn something cool").


The DevelopersResource accepts the input, then calls Developer#validate:

public class DevelopersResource {

    public String newDeveloper(Developer developer) {
        return developer.language + " " + developer.age;


curl -i -XPOST -d'{"language":"java","age":42}' -H"Content-type: application/json" -H"Accept: application/json" (...))/jsonb-validation/resources/developers


HTTP/1.1 200 OK
X-Powered-By: Servlet/4.0
Content-Type: application/json
Date: Fri, 14 Dec 2018 08:40:24 GMT
Content-Language: en-US
Content-Length: 7

java 42%      


curl -i -XPOST -d'{"language":"basic"}' -H"Content-type: application/json" -H"Accept: application/json" http://localhost:9080/jsonb-validation/resources/developers


HTTP/1.1 400 Bad Request
X-Powered-By: Servlet/4.0
reason: Learn something cool
Date: Fri, 14 Dec 2018 08:42:43 GMT
Content-Length: 0
Content-Language: en-US
Connection: Close    

ThinWAR size: 4.7kB, deployed with: WAD

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:

NEW workshops: MicroProfile with Quarkus and Micro Frontends with Web Components at MUC airport the podcast:

Stay in touch:


Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments