Selecting a View and Returning a Model at the Same Time

By returning an instance of org.springframework.web.servlet.ModelAndView, it is possible to specify a view name, add model attributes or set the HTTP response status at the same time.

An example can be found in the BlogPostController provided in the code repository for this chapter:

@GetMapping("/blogpost/{slug}")
public ModelAndView displayBlogPostBySlug(@PathVariable String
slug)
throws BlogPostNotFoundException {
BlogPost blogPost = blogPostService.findBlogPostBySlug(slug)
.orElseThrow(() -> new BlogPostNotFoundException("Blog
post with slug " + slug + " could not be found"));

return new ModelAndView("/blogposts/details", "blogPost",
blogPost);
}

This method returns the following information:

The view name /blogposts/details.

A model attribute called blogPost containing the actual blog post.