Quick Spring MVC question: If I don't return a model, how come I can still render a view via the response?
I 开发者_开发知识库can use:
return new ModelAndView(viewName, model);
Or I use:
response.setContentType("text/plain");
response.getWriter().print("Hello World!");
Now where's the difference n design, other that I dont need a JSP in the second solution. But I could also output a flestream right?
Maybe I just need a little bit more understanding. Hope some of you can help! Thanks!
MVC is about separing concerns. So you have three components for eachs request/response interaction. The data itself, the view for displaying the data, and the controller who is the master of puppets.
That's the model so you should use the three of them if they apply (by example, if you have a static page it doesn't have a model at all... it doesn't have a model to display, only HTML).
In some cases you can write directly from the controller, letting the controller to decide view and model. It's useful in the cases when there's no point to program a separate view like the case you point: a file output.
Anyway you could program a separate view. Something like FileOutputView, that receives the file or path or stream to output. That way the class that decides the rendering would be separated from the controller. But in this case there's little benefit in being such a purist.
I said program before because the view is responsible for rendering, but it doesn't have to be necesarily a declarative type of view, like JSP. Of course JSP will be the 99% of the time.
Yes you can output any content type. Do not forget to return null in this case.
精彩评论