7

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?

deamon
  • 89,107
  • 111
  • 320
  • 448

2 Answers2

3

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

yegor256
  • 102,010
  • 123
  • 446
  • 597
-2

Use @FormParam("count") Integer count

that will work.

Tommy
  • 1