java – 避免Spring MVC控制器中的NumberFormatException

在我的
Spring MVC控制器中,我有一个这样的方法:

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

当我传递一个字符串作为我的参数的值时,我显然得到一个NumberFormatException:

Failed to convert value of type ‘java.lang.String’ to required type ‘int’; nested exception is java.lang.NumberFormatException: For input string: “test”

那很清楚……

因此,我正在尝试找到一种方法,以便在发生此错误时将用户重定向到默认页面.有没有一种通用的方法来实现这一目标?

目前我正在考虑使用String代替int来映射我的param,检查这是否可解析为int然后切换到适当的逻辑,但这似乎是一种解决方法,而不是解决方案……

有没有更优雅的方法来处理这个问题并为我的参数保持正确的类型绑定?

最佳答案 请查看@Valid注释.希望这可以帮助.此批注有助于为请求参数添加更多验证.

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

点赞