Spring @MVC和@RequestParam验证 [英] Spring @MVC and @RequestParam validation

查看:80
本文介绍了Spring @MVC和@RequestParam验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to use the @RequestParam annotation like so:

@RequestMapping
public void handleRequest( @RequestParam("page") int page ) {
   ...
}

但是,如果用户摆弄URL参数并尝试转到页面"abz"或非数字内容,我想显示第1页.现在,我能使Spring做的最好的事情就是返回500.是否有一种方法可以干净地重写此行为,而不必将参数作为String接收?

However, I want to show page 1 if the user fiddles with the URL parameters and tries to go to page "abz" or something non-numerical. Right now, the best I can get Spring to do is return a 500. Is there a way to override this behavior cleanly without having to take in the parameter as a String?

我查看了@ExceptionHandler批注,但设置为@ExceptionHandler(TypeMismatchException.class)时似乎没有任何作用.不知道为什么不这么做.

I looked at the @ExceptionHandler annotation, but it doesn't seem to do anything when I set I use @ExceptionHandler(TypeMismatchException.class). Not sure why not.

建议?

P.S.额外的问题:Spring MVC被称为Spring MVC.带注释的Spring MVC是否仅称为Spring @MVC? Google将它们视为相同的名称,这很烦人.

P.S. Bonus question: Spring MVC is called Spring MVC. Is Spring MVC with annotations just called Spring @MVC? Google treats them as the same name, which is annoying.

推荐答案

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

Since Spring 3.0, you can set a ConversionService. @InitBinder's value specifies a particular parameter to apply that service to:

@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);
}

这篇关于Spring @MVC和@RequestParam验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆