Spring @MVC和@RequestParam验证

Bra*_*ugh 7 spring spring-mvc

我想像这样使用@RequestParam注释:

@RequestMapping
public void handleRequest( @RequestParam("page") int page ) {
   ...
}
Run Code Online (Sandbox Code Playgroud)

但是,如果用户摆弄URL参数并尝试转到页面"abz"或非数字的东西,我想显示第1页.现在,我可以让Spring做的最好的事情是返回500.有没有办法干净地覆盖这个行为,而不必将参数作为字符串接受?

我查看了@ExceptionHandler注释,但是当我设置使用时它似乎没有做任何事情@ExceptionHandler(TypeMismatchException.class).不知道为什么不.

建议?

PS Bonus问题:Spring MVC被称为Spring MVC.带有注释的Spring MVC是否叫做Spring @MVC?谷歌将它们视为同名,这很烦人.

Jan*_*ing 10

ConversionService是一个很好的解决方案,但是如果你给你的请求一个空字符串就缺少一个值?page=.RinitService根本就没有被调用,但page被设置为null(如果是Integer)或抛出异常(如果是int)

这是我的首选解决方案:

@RequestMapping
public void handleRequest( HttpServletRequest request ) {
    int page = ServletRequestUtils.getIntParameter(request, "page", 1);
}
Run Code Online (Sandbox Code Playgroud)

这样,您始终拥有有效的int参数.


axt*_*avt 8

从Spring 3.0开始,你可以设置一个ConversionService.@InitBindervalue指定特定参数到该服务适用于:

@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);
}
Run Code Online (Sandbox Code Playgroud)