Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form input validation with JAX-RS

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?

like image 849
deamon Avatar asked May 14 '10 09:05

deamon


1 Answers

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

like image 106
yegor256 Avatar answered Nov 11 '22 04:11

yegor256