This example demonstrates a simple Bean Validation (JSR-349) example with Jersey on the backend and AngularJs on the frontend.
Note: There is no validation on the frontend side, every error displayed is recognized on the backend.
The mapping of the URI path space is presented in the following table:
URI path | Resource class | HTTP methods | Allowed values |
---|---|---|---|
/api/contact | ContactCardResource | GET, POST, DELETE | |
/api/contact/{id} | ContactCardResource | GET, DELETE | id - positive number |
/api/contact/search/{searchType}?q={searchValue} | SearchResource | GET | searchType - (name|phone|email) searchValue - non empty string |
Application is configured by using web.xml, which registers javax.ws.rs.core.Application descendant to get classes and singletons from it (see class MyApplication). Bean Validation annotations are present on resource classes (see ContactCardResource, SearchResource) as well as on the domain class (see ContactCard).
When curl
(see examples below) is used for sending requests to the server, one can see how to affect the media type of returned validation errors (if any).
Allowed media types for validation errors entities are: "text/plain"/"text/html" or "application/json"/"application/xml" (appropriate provider has to be registered to transform errors into JSON/XML)
Note: jersey.config.beanValidation.enableOutputValidationErrorEntity.server
init parameter (web.xml
) has to be enabled to let Jersey know
that it should send validation errors as a Response entities (this behavior if disabled by default).
Run the example as follows:
mvn clean package jetty:run
This deploys current example using Jetty. You can access the application at http://localhost:8080/bean-validation-webapp
You can access resources of this application also using curl:
curl -v -H "Accept: application/json" http://localhost:8080/bean-validation-webapp/api/contact/424242
In this example you should see JSON array returned with one error - "Contact with given ID does not exist.".
curl -v http://localhost:8080/bean-validation-webapp/api/contact/424242
In this example you should see the same error but as a plain text.
This examples is using following (3-rd party) front-end frameworks: