Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Spring MVC controller method parameter work?

I created a Spring MVC project using a template that is created from the STS and this is what is generated in the controller:

@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
    //stuff
}

My question is, how does the locale and model variable get passed into the home method?

Also, what are the possible options for the objects that can be passed to the method?

like image 635
ryanprayogo Avatar asked Dec 04 '11 03:12

ryanprayogo


2 Answers

The general answer is "Spring magic"; however, "Supported handler method arguments and return types" in the MVC chapter of the Spring reference guide has the exact answers to your questions.

like image 134
Ryan Stewart Avatar answered Oct 11 '22 16:10

Ryan Stewart


The technical answer is through the use of SpringMVC HandlerAdapter mechanism.

By way of spring's DispatcherServlet, a Handler adapter is created and configured for each dispatched request.

I think the "spring magic" in this case is the AnnotationMethodHandlerAdapter located in the spring mvc packages. This adapter basically will be "mapped" to an HTTP request based on HTTP paths, HTTP methods and request parameters tied to the request.

So essentialy when the spring dispatcher servlet identifies a request with path "/", it will check for methods in it's container annotated with the RequestMapping annotation.

In your case it find's it...

Then the real magic begins...

Using java reflection, Spring will then resolve the arguments of your controller method. So in your case the Locale and model will automatically be passed to you. If you included another web like parameter, such as HttpSession, that will be passed to you.

like image 25
Roy Kachouh Avatar answered Oct 11 '22 15:10

Roy Kachouh