Fixing custom error page circumvention and RequestParam Validation

时间:2015-05-24 20:34:31

标签: html spring

I am trying to make it so there is no possibility of my users getting onto an error page (400). I have the following as view side input fields:

<input type="number" min="0" name="id" class="form-control" id="id">

Now it seems that it is still possible to avoid my custom error page by typing a number like this: 1. / 1,0 / 2.00 / 2,00 => those seem to be accepted by type="number"

Spring does not seem to convert those values into long, and thus generates a 400 error. In my controller I have

@RequestParam("id") long userID

I think there are 2 possible approaches to this issue:

Values get recognised at the view => possibly adding extra configuration so that values like 2.0 and 1,00 are not accepted. But I have not yet found a way to do so

Or I should try to tackle it at the spring side => Validating the RequestParam. Is there a way to validate a request param without using bean validation but in a similar fashion? (isn't it a bit ridiculous to use Bean validation and create an object just for validating a long field?).

Would also be interested in knowing what the standard way of validating RequestParams is in general, without having to create a Java Bean if there is a single field, which seems quite pointless.

1 个答案:

答案 0 :(得分:0)

As you noted, Spring has trouble converting certain number formats to Long. A solution that works with most formats is to accept a String in your function and to use the standard libraries to convert the input to a Long.

Try something like this:

public ModelAndView addItem(@RequestParam("id") String userID){
    Long id = -1;
    try {
        id = Long.parseLong(userID);
    } catch (NumberFormatException e){
        //handle error
    }
    if(id != -1){
        //continue  
    }
    //return ...
}