views:

182

answers:

1

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?

A: 

I think it's certainly valid for JAX-RS to throw such status code, because it matches the right request maping and the HTTP verb.

There are 2 possible solutions:-

  1. How about making the count variable as String, instead of int? This way, if your use enters some illegal values, you can handle it in your code rather than having JAX-RS to convert it.

    @POST
    public void create(@FormParam("count") String count) {
       // ... do a try catch when converting the String count to int
    }
    
  2. Perhaps, you can forgo the parameter and handle it programatically in your code. I personally don't like this way because it makes the code hard to understand and less self documented.

    @POST
    public void create() {
      // ... get the count programmatically through request
    }
    

Hope this helps.

limc