Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 974
Govinda Sakhare Avatar asked Oct 27 '25 20:10

Govinda Sakhare


1 Answers

  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

like image 118
Master Slave Avatar answered Oct 29 '25 10:10

Master Slave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!