Spring @MVC和@RequestParam验证
问题内容:
我想像这样使用@RequestParam批注:
@RequestMapping
public void handleRequest( @RequestParam("page") int page ) {
...
}
但是,如果用户摆弄URL参数并尝试转到页面“
abz”或非数字内容,我想显示页面1。现在,我能使Spring做的最好的事情就是返回500。是否有一种方法可以干净地重写此行为,而不必将参数作为String接收?
我查看了@ExceptionHandler批注,但设置我使用时似乎没有任何作用@ExceptionHandler(TypeMismatchException.class)
。不知道为什么不。
有什么建议吗?
PS奖金问题:Spring MVC称为Spring MVC。带有注释的Spring MVC是否仅称为Spring
@MVC?Google将它们视为相同的名称,这很烦人。
问题答案:
从Spring
3.0开始,您可以设置ConversionService
。@InitBinder
的value
指定了一个特定的参数来将该服务应用于:
@InitBinder("page")
public void initBinder(WebDataBinder binder) {
FormattingConversionService s = new FormattingConversionService();
s.addFormatterForFieldType(Integer.class, new Formatter<Integer>() {
public String print(Integer value, Locale locale) {
return value.toString();
}
public Integer parse(String value, Locale locale)
throws ParseException {
try {
return Integer.valueOf(value);
} catch (NumberFormatException ex) {
return 1;
}
}
});
binder.setConversionService(s);
}