Govinda Sakhare
Govinda Sakhare

Reputation: 5726

How request parameter binding and type conversion works in spring-mvc?

I am not understanding the flow of Spring MVC, Here are some doubts which I am facing.

@RequestMapping(value = "/addUser",method = RequestMethod.POST)
public ModelAndView addUser(@RequestParam("name") String name, @RequestParam("age") Integer age)
{
   // business logic
}

Model attribute binding

@RequestMapping(method = RequestMethod.POST, value = "doLogin")
public ModelAndView doLogin( @ModelAttribute("user") User userModel, HttpSession httpSession)
{

}

Upvotes: 4

Views: 1407

Answers (1)

Master Slave
Master Slave

Reputation: 28569

  1. When you annotate a method with @RequestMapping, a RequestMappingHandlerAdapter will register built-in argument resolvers.

  2. The arguments of the handler method will be scanned, and based on the type or annotation an appropriate argument resolver will kick-in. For example, for the @RequestParam annotation, an RequestParamMethodArgumentResolver will be called

  3. An argument resolver guides further the conversion and binding if applicable. The conversion is handled by an appropriate implementation of the Converter or PropertyEditor. The binding is handled by an appropriate instance of DataBinder. For the case of RequestParamMethodArgumentResolver and e.g. @RequestParam("age"), a NumberEditor guides the conversion, and a WebDataBinder guides the binding.

Different cases that you have in your example, are all a subject of the above flow, but different argument resolvers kick in e.g. ModelAttributeMethodProcessor, different converters of editors kick in (you can register custom ones for custom types, or for the User a default constructor will be called etc.)

About the singleton dilemma, it refers to a single instance of the component, and it concerns only the instance variables of the component. Methods, and arguments within are OK to be new instance it plays no role from the singleton perspective

Upvotes: 8

Related Questions