I want many of my controllers to create and return ModelMaps and to have these ModelMaps subsequently sent to/processed by a JsonView. (These controllers will service AJAX requests.) I assume I need setup a ViewResolver; what is the best way to do this? Is there a better alternative to Spring-Json View?
EDIT:
How do I wire a view when my controller returns ModelMap objects rather than ModelAndView objects?
I'm not sure if it's a 'better' alternative to spring-json, but with Spring 3.0, you can just annotate some methods in your Controller, and it will return json or xml based on the HTTP Accept header.
See this blog post for more information.
What is the problem with using spring-json view?
This seems like the exact way you would want to handle something like this:
Your controller is ignorant of the view technology that will be used, it just returns a viewname and the data (model)
You configure a view resolver to transform this model into JSON (or HTML, or Excel, or whatever you would like)
/**
* Custom handler for displaying vets.
* Note that this handler returns a plain {#link ModelMap} object instead of
* a ModelAndView, thus leveraging convention-based model attribute names.
* It relies on the RequestToViewNameTranslator to determine the logical
* view name based on the request URL: "/vets.do" -> "vets".
* #return a ModelMap with the model attributes for the view
*/
#RequestMapping("/vets.do")
public ModelMap vetsHandler() {
return new ModelMap(this.clinic.getVets());
}
It relies on the RequestToViewNameTranslator to determine the logical view name.
Related
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
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
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.
IN below code, we are adding attribute to model object which is passed as argument. But how come model.addAttribute() adds the value to list.jsp .Basically i want to know how the name values passed to list.jsp
Because we are not returning model object rather returning "list". so how the value is passed to list.jsp?
#Controller
#RequestMapping("/movie")
public class MovieController {
#RequestMapping(value="/{name}", method = RequestMethod.GET)
public String getMovie(#PathVariable String name, ModelMap model) {
model.addAttribute("movie", name);
return "list";
}
}
list.jsp is as follows
<html>
<body>
<h1>Spring 3 MVC REST web service</h1>
<h3>Movie Name : ${movie}</h3>
</body>
</html>
Reflection! The DispatcherServlet do all the hard work for you. Probably the model will be an attribute of the response object (HttpServletResponse)
Inside the View (you JSP in this particular case), you'll have available the Model object (you loaded in the controller). It will use the data inside the model to render it using EL expressions. Your view will call getters by Reflection invoking the same field name you used.
View is where the data in the Model is rendered as the required
output for the client. SpringMVC provides many implementations of
View to generate different output such as JSP,Excel, PDF, XML and etc.
DispatcherServlet will invoke render method from selected View
implementation to generate the output to be returned to the client.
Further info
Spring adds model attributes to the ServletRequest attributes. See source code for details.
I have to build a website in MVC pattern.
I have a "showuser.jsp" view, I can access the Model (DAO) in order to get all the users,
or my controller should pass this information to my view?
A typical sequence of MVC flow is as follows
User sends a page view request
Controller receives the request
Controller queries the Model for the data
Modelreturns the data (List of users in your case)
Controller passes this data to the selected View (showuser.jsp) (generally as request/session attribute)
The View is rendered and returned to the user.
This is nicely depicted in the following image:
I hope this answers your questions.
Normally controller fills model for the view (JSP).
You controller should call DAO (even better if you have Service layer where all the business logic is implemented. Then controller calls the Service which may have one or mode DAO). And store the info in model to be represented on the jsp.
This should be seamless. The view should not be aware of the model as such but it should be passed through the controller, a common technique in Spring MVC would be to pass a hibernate object through the controller which would then get converted to JSON.
The View would then render this JSON object and parse it appropriately. In your example your controller could pass to the view a list of User objects which you could then parse if it was an array of JSON objects.
Your view should call a controller, which would return the response from either the DAO or Service layer (depending on your business logic requirements).
In the MVC pattern the model and view should no be aware of each other. The model and view are bound together by a controller. So the controller should pass the model to the view.
To put it rather simply in code:
class View{}
class Model{}
class Controller{
View view = new View();
Model model = new Model();
public void controllerMethod(){
//pass model to view
}
}