I want to use JAX-RS REST services as a back-end for a web application used directly by humans with browsers. Since humans make mistakes from time to time I want to validate the form input and redisplay the form with validation message, if something wrong was entered. By default JAX-RS sends a 400 or 404 status code if not all or wrong values were send.
Say for example the user entered a "xyz" in the form field "count":
@POST
public void create(@FormParam("count") int count) {
...
}
JAX-RS could not convert "xyz" to int
and returns "400 Bad Request".
How can I tell the user that he entered an illegal value into the field "count"? Is there something more convenient than using Strings everywhere and perform conversation by hand?
I would recommend to use AOP, JSR-303, and JAX-RS exception mappers for example:
import javax.validation.constraints.Pattern;
@POST
public void create(@FormParam("count") @Pattern("\\d+") String arg) {
int count = Integer.parseInt(arg);
}
Then, define a JAX-RS exception mapper that will catch all ValidationException
-s and redirect users to the right location.
I'm using something similar in s3auth.com form validation with JAX-RS: https://github.com/yegor256/s3auth/blob/master/s3auth-rest/src/main/java/com/s3auth/rest/IndexRs.java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With