Validating form input using JAX-RS

I want to use JAX-RS REST services as the background for a web application used directly by people with browsers. Since people make mistakes from time to time, I want to check the form input and re-display the form with a validation message if something is wrong. By default, JAX-RS sends a 400 or 404 status code if all or incorrect values ​​have not been sent.

Say, for example, the user entered the field "xyz" in the form field "count":

@POST public void create(@FormParam("count") int count) { ... } 

JAX-RS was unable to convert "xyz" to int and returns "400 Bad Request".

How can I tell the user that he entered an invalid value in the "count" field? Is there anything more convenient than using strings all over the world and doing a conversation manually?

+7
java validation forms jax-rs
source share
2 answers

I would recommend using AOP, JSR-303 and JAX-RS, 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 mapping mechanism that catches all ValidationException -s and redirects users to the right place.

I use something like this in s3auth.com form validation using JAX-RS: https://github.com/yegor256/s3auth/blob/master/s3auth-rest/src/main/java/com/s3auth/rest/ Indexrs.java

+3
source share

Using @FormParam ("count") Integer

which will work.

-2
source share

All Articles