Question

I am trying to build RESTful web service by using spring 4.0

I have a controller:

    @Controller
    @RequestMapping("test")  
    public class Controller{
          @RequestMapping("fetch",method=RequestMethod.GET)
          @ResponseStatus(value=HttpStatus.OK)
          @ResponseBody
          public ResultResponse fetchController(ResultRequest req){
                 if((req.getName).equals("John"))
                     return new ResultResponse(100);
                  else
                     return new ResultResponse(0);
          }
    }

and my ResultRequest.class

    public class ResultRequest{
         private String name;
            //getter,setter
    }

If I hit the url to //host//contextPath/test/fetch?name=John

the controller will return the object ResultResponse(100)

my question is, there no @RequestParam or other annotation in the request parameter, how does the spring controller know to set the query parameter "name" as the property of wrapper class ResultRequest ?

Thanks

Was it helpful?

Solution

Spring uses implementations of an interface called HandlerMethodArgumentResolver for resolving arguments to pass to handler methods, ie. methods annotated with @RequestMapping.

One of these is a ModelAttributeMethodProcessor. Its javadoc states

Resolves method arguments annotated with @ModelAttribute and handles return values from methods annotated with @ModelAttribute.

Model attributes are obtained from the model or if not found possibly created with a default constructor if it is available. Once created, the attributed is populated with request data via data binding and also validation may be applied if the argument is annotated with @javax.validation.Valid.

When this handler is created with annotationNotRequired=true, any non-simple type argument and return value is regarded as a model attribute with or without the presence of an @ModelAttribute.

Spring registers two objects of this type. One to handle parameters annotated with @ModelAttribute and one to handle ones without.

Further reading:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top