docs
View resolvers for rendering server-side templates and views including JSP, Thymeleaf, FreeMarker, and other template engines. Provides the ViewResolver and View interfaces along with ModelAndView class for managing model data and view selection.
Strategy interface for resolving view names to View implementations.
/**
* Interface to be implemented by objects that can resolve views by name.
*
* View state doesn't change during the running of the application,
* so implementations are free to cache views.
*
* Implementations are encouraged to support internationalization,
* i.e. localized view resolution.
*/
public interface ViewResolver {
/**
* Resolve the given view by name.
*
* @param viewName name of the view to resolve
* @param locale the Locale in which to resolve the view
* @return the View object, or null if not found
* @throws Exception if the view cannot be resolved
*/
View resolveViewName(String viewName, Locale locale) throws Exception;
}Interface that renders a view given a model.
/**
* MVC View for a web interaction. Implementations are responsible for rendering
* content, and exposing the model.
*
* A single view can be used by multiple controllers, and is not thread-safe.
* Implementations should be JavaBeans, to allow for convenient configuration
* as Spring-managed bean instances. State should not be maintained in the view
* implementations but rather in the model.
*/
public interface View {
/**
* Name of the request attribute that contains the response status code.
*/
String RESPONSE_STATUS_ATTRIBUTE = View.class.getName() + ".responseStatus";
/**
* Name of the request attribute that contains a Map with path variables.
*/
String PATH_VARIABLES = View.class.getName() + ".pathVariables";
/**
* The ContentType for the view if predetermined.
*/
String SELECTED_CONTENT_TYPE = View.class.getName() + ".selectedContentType";
/**
* Return the content type of the view, if predetermined.
*
* Can be used to check the view's content type upfront,
* i.e. before an actual rendering attempt.
*
* @return the content type String (optionally including a character set),
* or null if not predetermined
*/
default String getContentType() {
return null;
}
/**
* Render the view given the specified model.
*
* The first step will be preparing the request: In the JSP case,
* this would mean setting model objects as request attributes.
* The second step will be the actual rendering of the view,
* for example including the JSP via a RequestDispatcher.
*
* @param model a Map with name Strings as keys and corresponding model
* objects as values (Map can also be null in case of empty model)
* @param request current HTTP request
* @param response he HTTP response we are building
* @throws Exception if rendering failed
*/
void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
throws Exception;
}Holder for both Model and View in the web MVC framework.
/**
* Holder for both Model and View in the web MVC framework.
* Note that these are entirely distinct. This class merely holds
* both to make it possible for a controller to return both model
* and view in a single return value.
*
* Represents a model and view returned by a handler, to be resolved
* by a DispatcherServlet. The view can take the form of a String
* view name which will need to be resolved by a ViewResolver object;
* alternatively a View object can be specified directly. The model
* is a Map, allowing the use of multiple objects keyed by name.
*/
public class ModelAndView {
/**
* Default constructor for bean-style usage.
*/
public ModelAndView() {}
/**
* Convenient constructor when there is no model data to expose.
*
* @param viewName name of the View to render
*/
public ModelAndView(String viewName) {}
/**
* Convenient constructor when there is no model data to expose.
*
* @param view the View object to render
*/
public ModelAndView(View view) {}
/**
* Create a new ModelAndView given a view name and a model.
*
* @param viewName name of the View to render
* @param model a Map of model names (Strings) to model objects
*/
public ModelAndView(String viewName, Map<String, ?> model) {}
/**
* Convenient constructor to take a single model object.
*
* @param viewName name of the View to render
* @param modelName name of the single entry in the model
* @param modelObject the single model object
*/
public ModelAndView(String viewName, String modelName, Object modelObject) {}
/**
* Create a new ModelAndView given a View object and a model.
*
* @param view the View object to render
* @param model a Map of model names (Strings) to model objects
*/
public ModelAndView(View view, Map<String, ?> model) {}
/**
* Convenient constructor to take a single model object.
*
* @param view the View object to render
* @param modelName name of the single entry in the model
* @param modelObject the single model object
*/
public ModelAndView(View view, String modelName, Object modelObject) {}
/**
* Set a view name for this ModelAndView, to be resolved by the
* DispatcherServlet via a ViewResolver. Will override any
* pre-existing view name or View.
*
* @param viewName the name of the View
*/
public void setViewName(String viewName) {}
/**
* Return the view name to be resolved by the DispatcherServlet
* via a ViewResolver, or null if we are using a View object.
*
* @return the view name, or null
*/
public String getViewName() {}
/**
* Set a View object for this ModelAndView. Will override any
* pre-existing view name or View.
*
* @param view the View object
*/
public void setView(View view) {}
/**
* Return the View object, or null if we are using a view name
* to be resolved by the DispatcherServlet via a ViewResolver.
*
* @return the View object, or null
*/
public View getView() {}
/**
* Indicate whether or not this ModelAndView has a view, either
* as a view name or as a direct View instance.
*
* @return whether this ModelAndView has a view
*/
public boolean hasView() {}
/**
* Return whether we use a view reference, i.e. true if the
* view has been specified via a name to be resolved by the
* DispatcherServlet via a ViewResolver.
*
* @return whether we use a view reference
*/
public boolean isReference() {}
/**
* Return the model map. May return null.
* Called by DispatcherServlet for evaluation of the model.
*
* @return the model map
*/
protected Map<String, Object> getModelInternal() {}
/**
* Return the underlying ModelMap instance (never null).
*
* @return the ModelMap instance
*/
public ModelMap getModelMap() {}
/**
* Return the model map. Never returns null.
* To be called by application code for modifying the model.
*
* @return the model map
*/
public Map<String, Object> getModel() {}
/**
* Add an attribute to the model.
*
* @param attributeName name of the object to add to the model
* @param attributeValue object to add to the model (never null)
* @return this instance for convenient chaining
*/
public ModelAndView addObject(String attributeName, Object attributeValue) {}
/**
* Add an attribute to the model using parameter name generation.
*
* @param attributeValue the object to add to the model (never null)
* @return this instance for convenient chaining
*/
public ModelAndView addObject(Object attributeValue) {}
/**
* Add all attributes contained in the provided Map to the model.
*
* @param modelMap a Map of attributeName -> attributeValue pairs
* @return this instance for convenient chaining
*/
public ModelAndView addAllObjects(Map<String, ?> modelMap) {}
/**
* Clear the state of this ModelAndView object.
* The object will be empty afterwards.
*/
public void clear() {}
/**
* Return whether this ModelAndView object is empty,
* i.e. whether it does not hold any view and does not contain a model.
*
* @return whether this ModelAndView is empty
*/
public boolean isEmpty() {}
/**
* Return whether this ModelAndView object is empty as far as it has been cleared.
*
* @return whether this ModelAndView was cleared
*/
public boolean wasCleared() {}
/**
* Set the HTTP status to use for the response.
*
* @param status the HTTP status code
*/
public void setStatus(HttpStatus status) {}
/**
* Return the configured HTTP status for the response, if any.
*
* @return the HTTP status code, or null
*/
public HttpStatus getStatus() {}
}Usage Example:
@Controller
@RequestMapping("/products")
public class ProductViewController {
@GetMapping
public ModelAndView listProducts() {
List<Product> products = productService.findAll();
return new ModelAndView("product/list", "products", products);
}
@GetMapping("/{id}")
public ModelAndView viewProduct(@PathVariable Long id) {
Product product = productService.findById(id);
ModelAndView mav = new ModelAndView("product/detail");
mav.addObject("product", product);
mav.addObject("relatedProducts", productService.findRelated(id));
return mav;
}
@GetMapping("/new")
public ModelAndView newProductForm() {
ModelAndView mav = new ModelAndView();
mav.setViewName("product/form");
mav.addObject("product", new Product());
mav.addObject("categories", categoryService.findAll());
return mav;
}
@PostMapping
public ModelAndView createProduct(@ModelAttribute Product product) {
productService.save(product);
return new ModelAndView("redirect:/products");
}
}Convenient subclass of UrlBasedViewResolver that supports InternalResourceView (JSPs) and subclasses such as JstlView.
/**
* Convenient subclass of UrlBasedViewResolver that supports InternalResourceView
* (i.e. Servlets and JSPs) and subclasses such as JstlView.
*
* The view class for all views generated by this resolver can be specified via the
* "viewClass" property. See UrlBasedViewResolver's javadoc for details.
*
* The default is InternalResourceView, or JstlView if the JSTL API is present.
*/
public class InternalResourceViewResolver extends UrlBasedViewResolver {
/**
* Set whether to always include the view rather than forward to it.
* Default is "false".
*
* @param alwaysInclude whether to always include the view
*/
public void setAlwaysInclude(boolean alwaysInclude) {}
/**
* Set whether to expose the path variables Map as request attribute.
* Default is "true".
*
* @param exposePathVariables whether to expose path variables
*/
public void setExposePathVariables(boolean exposePathVariables) {}
/**
* Set whether to make all Spring beans in the application context accessible
* as request attributes, through lazy checking once an attribute gets accessed.
* Default is "false".
*
* @param exposeContextBeansAsAttributes whether to expose context beans
*/
public void setExposeContextBeansAsAttributes(boolean exposeContextBeansAsAttributes) {}
/**
* Specify the names of beans in the context which are supposed to be exposed.
* If this is non-null, only the specified beans are eligible for exposure as
* attributes.
*
* @param exposedContextBeanNames the names of beans to expose
*/
public void setExposedContextBeanNames(String... exposedContextBeanNames) {}
}Usage Example:
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
resolver.setOrder(1);
return resolver;
}
}ViewResolver that delegates to other view resolvers based on content negotiation.
/**
* Implementation of ViewResolver that resolves a view based on the request file name
* or Accept header.
*
* The ContentNegotiatingViewResolver does not resolve views itself, but delegates to
* other ViewResolvers. By default, these other view resolvers are picked up automatically
* from the application context, though they can also be set explicitly by using the
* viewResolvers property.
*/
public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport
implements ViewResolver, Ordered, InitializingBean {
/**
* Set the ContentNegotiationManager to use to determine requested media types.
*
* @param contentNegotiationManager the ContentNegotiationManager
*/
public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) {}
/**
* Set the view resolvers to be wrapped by this view resolver.
*
* @param viewResolvers the view resolvers
*/
public void setViewResolvers(List<ViewResolver> viewResolvers) {}
/**
* Set the default views to use when a more specific view cannot be found.
*
* @param defaultViews the default views
*/
public void setDefaultViews(List<View> defaultViews) {}
/**
* Whether to return HTTP Status 406 "Not Acceptable" if no suitable view can be
* found. Default is false.
*
* @param useNotAcceptableStatusCode whether to use 406 status
*/
public void setUseNotAcceptableStatusCode(boolean useNotAcceptableStatusCode) {}
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {}
public void setOrder(int order) {}
@Override
public int getOrder() {}
}Implementation of Map for use when building model data for use with UI tools.
/**
* Implementation of Map for use when building model data for use with UI tools.
* Supports chained calls and generation of model attribute names.
*/
public class ModelMap extends LinkedHashMap<String, Object> {
public ModelMap() {}
public ModelMap(String attributeName, Object attributeValue) {}
public ModelMap(Object attributeValue) {}
public ModelMap addAttribute(String attributeName, Object attributeValue) {}
public ModelMap addAttribute(Object attributeValue) {}
public ModelMap addAllAttributes(Collection<?> attributeValues) {}
public ModelMap addAllAttributes(Map<String, ?> attributes) {}
public ModelMap mergeAttributes(Map<String, ?> attributes) {}
public boolean containsAttribute(String attributeName) {}
}