Avoid NumberFormatException in Spring MVC Controller

In my Spring MVC controller, I have a way like this:

public String myMethod(@RequestParam(defaultValue="0") int param) { ... }

      

When I pass a string as the value of mine param

, I obviously get NumberFormatException

:

Could not convert value of type 'java.lang.String' to required type 'int'; inested exception is java.lang.NumberFormatException: for input line: "test"

It is clear...

So I'm trying to find a way to redirect the user to the default page when this error occurs. Is there a general way to achieve this?

At the moment I am thinking of using String

instead int

to match mine param

, check if this is the syntactic answer to int

and then switch to the appropriate logic, but this seems to be a workaround, not a solution ...

Is there a more elegant way to handle this problem and keep the correct type binding for mine param

?

+3


source to share


2 answers


Finally I decided to add CustomNumberEditor

like this:



@InitBinder
public void registerNumbersBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Integer.class, new CustomNumberEditor(Integer.class, true){
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            try{
                super.setAsText(text);
            }catch (IllegalArgumentException ex){
                setValue(0);
            }
        }
    });
}

      

0


source


Please see the @Valid annotation. Hope this helps. This annotation helps to add additional checks for the request parameter.



https://spring.io/guides/gs/validating-form-input/

0


source







All Articles