简体   繁体   中英

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
}
  • How are the name and age field are being binded? I mean which spring module is doing it(any interceptor)?
  • How age field to converted to Integer ?
  • How User Object marked with @ModelAttribute in below 's example is getting assigned form field values ?

Model attribute binding

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

}
  • Which interceptor is injecting HttpSession object?
  • As User is marked as Singleton , then if I have 1000 users accessing my web application ain't every user will get a different object? then how is it singleton ?
  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 eg @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 eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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