Results 1 to 3 of 3

Thread: 2.5 - @RequestParam not behaving like it ought to

  1. #1
    Join Date
    Aug 2004
    Location
    Scotland
    Posts
    2

    Default 2.5 - @RequestParam not behaving like it ought to

    Hello

    I'm a little new to 2.5, but I suspect @RequestParam is throwing an exception when it shouldn't (with required=false, and when not passed a parameter). Here's my code:

    @RequestMapping("/")
    public ModelAndView index(
    @RequestParam(value="foo", required=false) int id) {
    ModelAndView mav = new ModelAndView("myview");
    mav.addObject("message", id);
    return mav;
    }

    Note the "required=false"! When called, I get the exception below.

    Looking at the source for AnnotationMethodHandlerAdapter I see on line 549:
    args[i] = converter.convertIfNecessary(paramValue, param.getParameterType());

    Either convertIfNecessary should not throw an exception on null param, or we need a check before this method (on paramRequired), or I'm wrong and misunderstanding something :-)

    Please advise.
    Thanks
    Jon

    org.springframework.web.util.NestedServletExceptio n: Request processing failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert value of type [null] to required type [int]; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [null] to required type [int]: no matching editors or conversion strategy found



    ...


    org.springframework.beans.TypeMismatchException: Failed to convert value of type [null] to required type [int]; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [null] to required type [int]: no matching editors or conversion strategy found
    org.springframework.beans.SimpleTypeConverter.conv ertIfNecessary(SimpleTypeConverter.java:50)

  2. #2
    Join Date
    Sep 2007
    Location
    Oceanside, CA
    Posts
    187

    Default

    Internally, the default CustomNumberEditor registered in Spring for the primitive int type does not allow empty or null values, so an exception can occur even when you specify "required=false" for @RequestParam. You could use the java.lang.Integer wrapper instead for your parameter type (which allows null/empty values), or possibly create a custom editor which sets a default value on the primitive parameter for an empty or null input. The following thread has more discussion on the latter approach:

    http://forum.springframework.org/showthread.php?t=28155
    Mike Bingham

  3. #3
    Join Date
    Aug 2004
    Location
    Scotland
    Posts
    2

    Default

    Thanks Mike - that did it..

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •