RequestMapping methods - supported return types

The RequestMapping methods support a varied range of return types. Thinking conceptually, a request mapping method should answer two questions:

  • What's the view?
  • What's the model that the view needs?

However, with Spring MVC, the view and model need not be explicitly declared at all times:

  • If a view is not explicitly defined as part of the return type, then it is implicitly defined.
  • Similarly, any model object is always enriched as detailed in the rules below.

Spring MVC uses simple rules to determine the exact view and model. A couple of important rules are listed as follows:

  • Implicit enriching of the Model: If a model is part of the return type, it is enriched with command objects (including results from validation of the command objects). In addition, the results of methods with the @ModelAttribute annotations are also added to the model.
  • Implicit determination of the View: If a view name is not present in the return type, it is determined using DefaultRequestToViewNameTranslator. By default, DefaultRequestToViewNameTranslator removes the leading and trailing slashes as well as the file extension from the URI; for example, the display.html becomes display.

The following are some of the return types that are supported on Controller methods with Request Mapping:

Return Type

What happens?

ModelAndView

The object includes a reference to the model and the view name.

Model

Only Model is returned. The view name is determined using DefaultRequestToViewNameTranslator.

Map

A simple map to expose a model.

View

A view with a model implicitly defined.

String

Reference to a view name.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset