简体   繁体   English

Spring @MVC和@RequestParam验证

[英]Spring @MVC and @RequestParam validation

I would like to use the @RequestParam annotation like so: 我想像这样使用@RequestParam注释:

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

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

I looked at the @ExceptionHandler annotation, but it doesn't seem to do anything when I set I use @ExceptionHandler(TypeMismatchException.class) . 我查看了@ExceptionHandler注释,但是当我设置使用@ExceptionHandler(TypeMismatchException.class)时它似乎没有做任何事情。 Not sure why not. 不知道为什么不。

Suggestions? 建议?

PS Bonus question: Spring MVC is called Spring MVC. PS Bonus问题:Spring MVC被称为Spring MVC。 Is Spring MVC with annotations just called Spring @MVC? 带有注释的Spring MVC是否叫做Spring @MVC? Google treats them as the same name, which is annoying. 谷歌将它们视为同名,这很烦人。

The ConversionService is a nice solution, but it lacks a value if you give an empty string to your request like ?page= The ConversionService is simply not called at all, but page is set to null (in case of Integer ) or an Exception is thrown (in case of an int ) ConversionService是一个很好的解决方案,但如果你给你的请求一个空字符串,它缺少一个值?page=根本不调用ConversionService,但是page设置为null (如果是Integer )或者Exception是抛出(如果是int

This is my preferred solution: 这是我的首选解决方案:

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

This way you always have a valid int parameter. 这样,您始终拥有有效的int参数。

Since Spring 3.0, you can set a ConversionService . 从Spring 3.0开始,您可以设置ConversionService @InitBinder 's value specifies a particular parameter to apply that service to: @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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM