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
?
source to share
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);
}
}
});
}
source to share