Spring @MVC and @RequestParam validation

后端 未结 2 743
一生所求
一生所求 2020-12-28 10:33

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

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

相关标签:
2条回答
  • 2020-12-28 10:59

    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)

    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.

    0 讨论(0)
  • 2020-12-28 11:04

    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);
    }
    
    0 讨论(0)
提交回复
热议问题