ModelAndView or ResponseEntity return type for controllers?

Viewed 961

So far in my experience with Spring I have mainly seen ResponseEntity return types for controllers. However, I have seen ModelAndView return types. Why would someone use ModelAndView over ResponseEntity or vice versa?

In other words, what are the benefits and negatives of either, as I can't really find a comparison of such online?

1 Answers

ResponseEntity is used for RestController, where you want to return a response (200, 400, etc..) with a payload (Json, etc..).

@GetMapping("/hello")
ResponseEntity<String> hello() {
    return new ResponseEntity<>("Hello World!", HttpStatus.OK);
}

ModelAndView is used for MVC Controller, where you return the view (HTML, jsp, etc..) templates with data fields set to values you fill the templates with.

Example: an HTML page named employeeDetails with two fields (employeeObj, msg)

ModelAndView model = new ModelAndView("employeeDetails");
model.addObject("employeeObj", new EmployeeBean(123));
model.addObject("msg", "Employee information.");
return model;
Related