The Model parameter in #RequestMapping method - java

Currently I am learning Spring specifically the Spring MVC part and I stumbled on thing I don't quite understand how does it work.
#RequestMapping("/foo")
public String foo(Model model){
// code here
return "foo";
}
The method above annotated with #RequestMapping receive the parameter with class Model and sometimes ModelAndView.
What I don't understand is where the Model parameter comes from and how the flow is from the spring configuration class (Such as WebConfig.java) which use the ComponentScan and a Bean of InternalResourceViewResolver.
I've been looking for sources and I don't find anything helpful for me, even the documentation, which makes me to ask here for the first time.
A direct explanation will be really helpful, or if there are any sources can be put the link here.
If it is from the documentation please mention which part/section it is because I might miss one or two thing.

The method above annotated with #RequestMapping receive the parameter
with class Model and sometimes ModelAndView.
The below post explains in detail about ModelAndView and Model
When to use ModelAndView vs Model in Spring?
where the Model parameter comes from
A Controller is typically responsible for preparing a model Map with data and selecting a view name but it can also write directly to the response stream and complete the request. View name resolution is highly configurable through file extension or Accept header content type negotiation, through bean names, a properties file, or even a custom ViewResolver implementation. The model (the M in MVC) is a Map interface, which allows for the complete abstraction of the view technology. You can integrate directly with template based rendering technologies such as JSP, Velocity and Freemarker, or directly generate XML, JSON, Atom, and many other types of content. The model Map is simply transformed into an appropriate format, such as JSP request attributes, a Velocity template model.
Reference - http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-arguments

Related

Are Spring Model objects (and their attributes) tied to their respective controller endpoints / templates?

I'm just starting with spring so please bear with me. I've just solved a bug in my code that was coming from my assumption that once an attribute is added to any Model object, it would also be available to the templating implementation at other endpoints.
#GetMapping("/user_page")
public String getUserPage( Model model ) {
Page page = new Page();
model.addAttribute("user_page", page);
return "user_page";
In my Thymeleaf template I was able to use this attribute fine at user_page.html. Now at another endpoint and template I was also trying to use this user_page attribute. Note that it was throwing some errors:
Exception evaluating SpringEL expression:
and
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'name' cannot be found on null
It looks like Thymeleaf couldn't find the user_page attribute.
but I also hadn't added a Model parameter to the controller that handled this other endpoint. After adding a Model to the method parameters and adding the page again model.addAttribute("user_page", page);, this time to the controller handling the different endpoint, the problem went away.
Is Spring autowiring non-singleton Model objects to these controllers? Why did I have to add the same page instance to the model twice? So are these Models tied specifically to the template (maybe even endpoint) that their respective controller returns?
Read Dispatcher Servlet Processing Sequence.
Are Spring Model objects (and their attributes) tied to their respective controller endpoints / templates?
There is no such a thing, as "Model's respective controller"; rather, a fresh instance of the Model's implementation gets instantiated each time, any handler method gets invoked.
When an HTTP request hits dispatcher servlet, and the latter passes the servlet request-response objects into the corresponding handler method, Spring MVC's infrastructure looks up the signature of corresponding handler method and passes a fresh instance of the Model (along with many others), if it is expected.
You can also use modelAttribute element in your template's form, and this way, you will directly bind the data to the handler method's Model parameter, having the argument being pre-filled with the form data. In this case, you can also enable Bean Validation.

Ways in which Controller (in Spring MVC) can provide the view name to DispatcherServlet?

I am working on a project, which is mainly using Spring framework.The views has been implemented using JSP and JSTLs.
Usually in various books / online tutorials which I read, the Controller class returns ModelAndView and based on what this object has, DispatcherServlet is able to return the correct view name.
Are there any other ways in which Controller (of Spring MVC) can specify the view name, for example returning a String?
Any pointer in this regards highly appreciated.
As Spring Documentation states:
All handler methods in the Spring Web MVC controllers must resolve to
a logical view name, either explicitly (e.g., by returning a String,
View, or ModelAndView) or implicitly (i.e., based on conventions)
So:
Is there any other way in which the Controller (in MVC part) can
specify the view name, for example returning a String?
Yes, you can just specify the view name as a String return value. Basically you can determine the view explicitly by returning:
A String representing the logical view name
An instance of ModelAndView
An instance of a View implementation, e.g. RedirectView

binding and working of spring form with the back end object in SpringMVC

I am new to SpringMvc. Could anyone please explain the binding and working of spring form with the back end object in SpringMVC.
some of the doubts are
Consider the scenario, there is a form which will take user details and it will be persisted to db
1) I have seen a controller which creates User's instances and adding the attribute to ModelMap. What is the use of that?
#Controller
#RequestMapping("/form.html")
public ModelAndView form(ModelMap map){
User user= new User();
map.addAttribute("user",user);
return new ModelAndView("form","command",map);
}
2) What is the use of command here? in the form page, this 'user' object will be available?
*form.jsp
<form:form.... action="formprocess.html" commandName="user"/>
(If I want to use 'user' should it have been already created as above?)
3) Why do we use #ModelAttribute? Why do we use Model instead of ModelMap?
#Controller
#RequestMapping("/formprocess.html")
public String form(#ModelAttribute("user"User user,Model model){
model.addAttribute("username",user.getUserName());
return "formprocess";
}
could anyone please explain or provide a link which has sufficient explanations
Regarding ModelMap, model map is used to pass certain data from you controller to the view which you delegate from that controller. You add attributes from controller and later on get attributes from view page.
Regarding commandName, commandName="user" this is something that the controller uses to map the form fields to a particular bean or POJO fields. So you do not have to manually get all the request parameters and set it yo pojos when a form is submitted and controller receives the event.
Regarding #ModelAttribute, since you use #ModelAttribute("user") as method parameter, spring container will look for a a command name user from request object and map it's properties to the pojos defined in #ModelAttribute viz in your case User class.
Regarding difference between Model and ModelMap :
ModelMap subclasses LinkedHashMap, and provides some additional conveniences to make it a bit easier to use by controllers
addAttribute can be called with just a value, and the map key is then inferred from the type.
The addAttribute methods all return the ModelMap, so you can chain method called together, e.g. modelMap.addAttribute('x', x).addAttribute('y',y)
The addAttribute methods checks that the values aren't null
The generic type of ModelMap is fixed at Map<String, Object>, which is the only one that makes sense for a view model.
So nothing earth-shattering, but enough to make it a bit nicer than a raw Map. Spring will let you use either one.
You can also use the Model interface, which provides nothing other than the addAttribute methods, and is implemented by the ExtendedModelMap class which itself adds further conveniences.

Why do I need to add #ResponseBody to my controller action?

According to Spring documentation, this annotation indicates that a method return value should be bound to the web response body. I understand that, and I've been using this for my ajax calls. However, I recently came across code that doesn't use the annotation.
So I guess my question really is why it works without the annotation?
Without the annotation, a different process takes place. Depending on the return type (you can find the defaults in this document) the response will be generated differently.
For example, if your return type is String, then, by default, the return value will be resolved as a View name, a ViewResolver will try to resolve and create a View object, and a RequestDispatcher will forward/include/redirect to it (ex. a jsp) so that the Servlet container can handle generating the response.
The actual interface that handles the return type is HandlerMethodReturnValueHandler and there are many implementations for each type. See here for more information.

controller in spring for form handling

I am newbie in spring. using spring 3.0 mvc.
I am creating a spring application, I have a login form,Any one please suggest what controller i should use, as when I am using SimpleFormController its saying deprecated,
Any specific controller I can use.
First of all as everybody already told you use annotation-base controller
secondly for creating a form you can use spring form taglib
thirdly you can create method like this
public String updateHouse(House house, #RequestParam("file") MultipartFile file, Model model) {
this is from my sample application. House object is auto generated from form. In my form I have fields of my House object and it is send to the method as object. #RequestParam allows me to fetch the file witch is uploaded via form (POST), Model is my view model.
As you can see it is easy :)
Why don't you try annotation-based controllers? They are easy and fun to use.
You can try annotation based controller. Please refer below link:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html

Categories

Resources