org.springframework.web.servlet.view
Class ContentNegotiatingViewResolver

java.lang.Object
  extended by org.springframework.context.support.ApplicationObjectSupport
      extended by org.springframework.web.context.support.WebApplicationObjectSupport
          extended by org.springframework.web.servlet.view.ContentNegotiatingViewResolver
All Implemented Interfaces:
Aware, ApplicationContextAware, Ordered, ServletContextAware, ViewResolver

public class ContentNegotiatingViewResolver
extends WebApplicationObjectSupport
implements ViewResolver, Ordered

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. Note that in order for this view resolver to work properly, the order property needs to be set to a higher precedence than the others (the default is Ordered.HIGHEST_PRECEDENCE.)

This view resolver uses the requested media type to select a suitable View for a request. This media type is determined by using the following criteria:

  1. If the requested path has a file extension and if the setFavorPathExtension(boolean) property is true, the mediaTypes property is inspected for a matching media type.
  2. If the request contains a parameter defining the extension and if the setFavorParameter(boolean) property is true, the mediaTypes property is inspected for a matching media type. The default name of the parameter is format and it can be configured using the parameterName property.
  3. If there is no match in the mediaTypes property and if the Java Activation Framework (JAF) is both enabled and present on the classpath, FileTypeMap.getContentType(String) is used instead.
  4. If the previous steps did not result in a media type, and ignoreAcceptHeader is false, the request Accept header is used.

Once the requested media type has been determined, this resolver queries each delegate view resolver for a View and determines if the requested media type is compatible with the view's content type). The most compatible view is returned.

Additionally, this view resolver exposes the defaultViews property, allowing you to override the views provided by the view resolvers. Note that these default views are offered as candicates, and still need have the content type requested (via file extension, parameter, or Accept header, described above). You can also set the default content type directly, which will be returned when the other mechanisms (Accept header, file extension or parameter) do not result in a match.

For example, if the request path is /view.html, this view resolver will look for a view that has the text/html content type (based on the html file extension). A request for /view with a text/html request Accept header has the same result.

Since:
3.0
Author:
Arjen Poutsma, Juergen Hoeller, Rossen Stoyanchev
See Also:
ViewResolver, InternalResourceViewResolver, BeanNameViewResolver

Field Summary
 
Fields inherited from interface org.springframework.core.Ordered
HIGHEST_PRECEDENCE, LOWEST_PRECEDENCE
 
Constructor Summary
ContentNegotiatingViewResolver()
           
 
Method Summary
protected  MediaType getMediaTypeFromFilename(String filename)
          Determines the MediaType for the given filename.
protected  MediaType getMediaTypeFromParameter(String parameterValue)
          Determines the MediaType for the given parameter value.
protected  List<MediaType> getMediaTypes(HttpServletRequest request)
          Determines the list of MediaType for the given HttpServletRequest.
 int getOrder()
          Return the order value of this object, with a higher value meaning greater in terms of sorting.
protected  void initServletContext(ServletContext servletContext)
          Subclasses may override this for custom initialization based on the ServletContext that this application object runs in.
 View resolveViewName(String viewName, Locale locale)
          Resolve the given view by name.
 void setDefaultContentType(MediaType defaultContentType)
          Set the default content type.
 void setDefaultViews(List<View> defaultViews)
          Set the default views to use when a more specific view can not be obtained from the ViewResolver chain.
 void setFavorParameter(boolean favorParameter)
          Indicate whether a request parameter should be used to determine the requested media type, in favor of looking at the Accept header.
 void setFavorPathExtension(boolean favorPathExtension)
          Indicate whether the extension of the request path should be used to determine the requested media type, in favor of looking at the Accept header.
 void setIgnoreAcceptHeader(boolean ignoreAcceptHeader)
          Indicate whether the HTTP Accept header should be ignored.
 void setMediaTypes(Map<String,String> mediaTypes)
          Set the mapping from file extensions to media types.
 void setOrder(int order)
           
 void setParameterName(String parameterName)
          Set the parameter name that can be used to determine the requested media type if the setFavorParameter(boolean) property is true.
 void setUseJaf(boolean useJaf)
          Indicate whether to use the Java Activation Framework to map from file extensions to media types.
 void setUseNotAcceptableStatusCode(boolean useNotAcceptableStatusCode)
          Indicate whether a 406 Not Acceptable status code should be returned if no suitable view can be found.
 void setViewResolvers(List<ViewResolver> viewResolvers)
          Sets the view resolvers to be wrapped by this view resolver.
 
Methods inherited from class org.springframework.web.context.support.WebApplicationObjectSupport
getServletContext, getTempDir, getWebApplicationContext, initApplicationContext, isContextRequired, setServletContext
 
Methods inherited from class org.springframework.context.support.ApplicationObjectSupport
getApplicationContext, getMessageSourceAccessor, initApplicationContext, requiredContextClass, setApplicationContext
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ContentNegotiatingViewResolver

public ContentNegotiatingViewResolver()
Method Detail

setOrder

public void setOrder(int order)

getOrder

public int getOrder()
Description copied from interface: Ordered
Return the order value of this object, with a higher value meaning greater in terms of sorting.

Normally starting with 0, with Integer.MAX_VALUE indicating the greatest value. Same order values will result in arbitrary positions for the affected objects.

Higher values can be interpreted as lower priority. As a consequence, the object with the lowest value has highest priority (somewhat analogous to Servlet "load-on-startup" values).

Specified by:
getOrder in interface Ordered
Returns:
the order value

setFavorPathExtension

public void setFavorPathExtension(boolean favorPathExtension)
Indicate whether the extension of the request path should be used to determine the requested media type, in favor of looking at the Accept header. The default value is true.

For instance, when this flag is true (the default), a request for /hotels.pdf will result in an AbstractPdfView being resolved, while the Accept header can be the browser-defined text/html,application/xhtml+xml.


setFavorParameter

public void setFavorParameter(boolean favorParameter)
Indicate whether a request parameter should be used to determine the requested media type, in favor of looking at the Accept header. The default value is false.

For instance, when this flag is true, a request for /hotels?format=pdf will result in an AbstractPdfView being resolved, while the Accept header can be the browser-defined text/html,application/xhtml+xml.


setParameterName

public void setParameterName(String parameterName)
Set the parameter name that can be used to determine the requested media type if the setFavorParameter(boolean) property is true. The default parameter name is format.


setIgnoreAcceptHeader

public void setIgnoreAcceptHeader(boolean ignoreAcceptHeader)
Indicate whether the HTTP Accept header should be ignored. Default is false.

If set to true, this view resolver will only refer to the file extension and/or parameter, as indicated by the favorPathExtension and favorParameter properties.


setUseNotAcceptableStatusCode

public void setUseNotAcceptableStatusCode(boolean useNotAcceptableStatusCode)
Indicate whether a 406 Not Acceptable status code should be returned if no suitable view can be found.

Default is false, meaning that this view resolver returns null for resolveViewName(String, Locale) when an acceptable view cannot be found. This will allow for view resolvers chaining. When this property is set to true, resolveViewName(String, Locale) will respond with a view that sets the response status to 406 Not Acceptable instead.


setMediaTypes

public void setMediaTypes(Map<String,String> mediaTypes)
Set the mapping from file extensions to media types.

When this mapping is not set or when an extension is not present, this view resolver will fall back to using a FileTypeMap when the Java Action Framework is available.


setDefaultViews

public void setDefaultViews(List<View> defaultViews)
Set the default views to use when a more specific view can not be obtained from the ViewResolver chain.


setDefaultContentType

public void setDefaultContentType(MediaType defaultContentType)
Set the default content type.

This content type will be used when file extension, parameter, nor Accept header define a content-type, either through being disabled or empty.


setUseJaf

public void setUseJaf(boolean useJaf)
Indicate whether to use the Java Activation Framework to map from file extensions to media types.

Default is true, i.e. the Java Activation Framework is used (if available).


setViewResolvers

public void setViewResolvers(List<ViewResolver> viewResolvers)
Sets the view resolvers to be wrapped by this view resolver.

If this property is not set, view resolvers will be detected automatically.


initServletContext

protected void initServletContext(ServletContext servletContext)
Description copied from class: WebApplicationObjectSupport
Subclasses may override this for custom initialization based on the ServletContext that this application object runs in.

The default implementation is empty. Called by WebApplicationObjectSupport.initApplicationContext(org.springframework.context.ApplicationContext) as well as WebApplicationObjectSupport.setServletContext(javax.servlet.ServletContext).

Overrides:
initServletContext in class WebApplicationObjectSupport
Parameters:
servletContext - the ServletContext that this application object runs in (never null)

resolveViewName

public View resolveViewName(String viewName,
                            Locale locale)
                     throws Exception
Description copied from interface: ViewResolver
Resolve the given view by name.

Note: To allow for ViewResolver chaining, a ViewResolver should return null if a view with the given name is not defined in it. However, this is not required: Some ViewResolvers will always attempt to build View objects with the given name, unable to return null (rather throwing an exception when View creation failed).

Specified by:
resolveViewName in interface ViewResolver
Parameters:
viewName - name of the view to resolve
locale - Locale in which to resolve the view. ViewResolvers that support internationalization should respect this.
Returns:
the View object, or null if not found (optional, to allow for ViewResolver chaining)
Throws:
Exception - if the view cannot be resolved (typically in case of problems creating an actual View object)

getMediaTypes

protected List<MediaType> getMediaTypes(HttpServletRequest request)
Determines the list of MediaType for the given HttpServletRequest.

The default implementation invokes getMediaTypeFromFilename(String) if favorPathExtension property is true. If the property is false, or when a media type cannot be determined from the request path, this method will inspect the Accept header of the request.

This method can be overridden to provide a different algorithm.

Parameters:
request - the current servlet request
Returns:
the list of media types requested, if any

getMediaTypeFromFilename

protected MediaType getMediaTypeFromFilename(String filename)
Determines the MediaType for the given filename.

The default implementation will check the media types property first for a defined mapping. If not present, and if the Java Activation Framework can be found on the classpath, it will call FileTypeMap.getContentType(String)

This method can be overridden to provide a different algorithm.

Parameters:
filename - the current request file name (i.e. hotels.html)
Returns:
the media type, if any

getMediaTypeFromParameter

protected MediaType getMediaTypeFromParameter(String parameterValue)
Determines the MediaType for the given parameter value.

The default implementation will check the media types property for a defined mapping.

This method can be overriden to provide a different algorithm.

Parameters:
parameterValue - the parameter value (i.e. pdf).
Returns:
the media type, if any