Custom input validation with JAX-RS and JSON-B (Java EE 8) 📎
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.
status(400).
header("reason", "Learn something cool").
build()
);
}
}
}
The DevelopersResource
accepts the input, then calls Developer#validate
:
@Path("developers")
public class DevelopersResource {
@POST
public String newDeveloper(Developer developer) {
developer.validate();
return developer.language + " " + developer.age;
}
}
Test:
curl -i -XPOST -d'{"language":"java","age":42}' -H"Content-type: application/json" -H"Accept: application/json" (...))/jsonb-validation/resources/developers
returns
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%
however
curl -i -XPOST -d'{"language":"basic"}' -H"Content-type: application/json" -H"Accept: application/json" http://localhost:9080/jsonb-validation/resources/developers
yields:
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: airhacks.io.