Why the annontation @ResponseBody along with the return value 'ModelAndView' doesn't work?
When I write some controllers in Spring Boot project, I want to use the annotation @ResponseBody
to test if the controller interface works normally, so I created a controller like this:
@ResponseBody
@GetMapping("/about")
public ModelAndView about(){
return new ModelAndView("about");
}
To test if this controller was working, I used the browser to test it. I didn't use the URL about.html
, so I expected the browser should have shown a JSON string to describe the ModelAndView
object. This isn't what happened; instead it showed an error that the dispatchServlet cannot resolve the template.
It seems like the annotation is not working. I cleared my cache, cleaned the project, and rebuilt it, but that didn't help. What am I doing wrong?
Check the doc and you will understand why this is not allowed.
public @interface ResponseBody Annotation that indicates a method return value should be bound to the web response body.
ModelAndView otherwise when returned contains 2 different information.
A) Model object which is passed to the view and can be accessed from the view
B) View (ex myView.jsp) which should be rendered and where the model object would be accessible for.
The @ResponseBody
shall be used when you pass to the user a single response with some data that you want to. The user expects to read only what you return from the controller.
The ModelAndView
shall be used when you pass to the user a dynamic view that you have defined in your application.
Those 2 are 2 separate scenarios.