org.springframework.web.servlet.view.velocity
Class VelocityView

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.AbstractView
              extended by org.springframework.web.servlet.view.AbstractUrlBasedView
                  extended by org.springframework.web.servlet.view.AbstractTemplateView
                      extended by org.springframework.web.servlet.view.velocity.VelocityView
All Implemented Interfaces:
BeanNameAware, InitializingBean, ApplicationContextAware, ServletContextAware, View
Direct Known Subclasses:
VelocityToolboxView

public class VelocityView
extends AbstractTemplateView

View using the Velocity template engine.

Exposes the following JavaBean properties:

Depends on a VelocityConfig object such as VelocityConfigurer being accessible in the current web application context, with any bean name. Alternatively, you can set the VelocityEngine object as bean property.

Note: Spring's VelocityView requires Velocity 1.3 or higher, and optionally Velocity Tools 1.0 or higher (depending on the use of DateTool and/or NumberTool).

Author:
Rod Johnson, Juergen Hoeller
See Also:
VelocityConfig, VelocityConfigurer, AbstractUrlBasedView.setUrl(java.lang.String), AbstractTemplateView.setExposeSpringMacroHelpers(boolean), setEncoding(java.lang.String), setVelocityEngine(org.apache.velocity.app.VelocityEngine), VelocityConfig, VelocityConfigurer

Field Summary
 
Fields inherited from class org.springframework.web.servlet.view.AbstractTemplateView
SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE
 
Fields inherited from class org.springframework.web.servlet.view.AbstractView
DEFAULT_CONTENT_TYPE
 
Fields inherited from class org.springframework.context.support.ApplicationObjectSupport
logger
 
Constructor Summary
VelocityView()
           
 
Method Summary
protected  org.apache.velocity.app.VelocityEngine autodetectVelocityEngine()
          Autodetect a VelocityEngine via the ApplicationContext.
protected  void checkTemplate()
          Check that the Velocity template used for this view exists and is valid.
protected  org.apache.velocity.context.Context createVelocityContext(java.util.Map<java.lang.String,java.lang.Object> model)
          Create a Velocity Context instance for the given model, to be passed to the template for merging.
protected  org.apache.velocity.context.Context createVelocityContext(java.util.Map<java.lang.String,java.lang.Object> model, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
          Create a Velocity Context instance for the given model, to be passed to the template for merging.
protected  void doRender(org.apache.velocity.context.Context context, javax.servlet.http.HttpServletResponse response)
          Render the Velocity view to the given response, using the given Velocity context which contains the complete template model to use.
protected  void exposeHelpers(org.apache.velocity.context.Context velocityContext, javax.servlet.http.HttpServletRequest request)
          Expose helpers unique to each rendering operation.
protected  void exposeHelpers(org.apache.velocity.context.Context velocityContext, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
          Expose helpers unique to each rendering operation.
protected  void exposeHelpers(java.util.Map<java.lang.String,java.lang.Object> model, javax.servlet.http.HttpServletRequest request)
          Expose helpers unique to each rendering operation.
protected  void exposeToolAttributes(org.apache.velocity.context.Context velocityContext, javax.servlet.http.HttpServletRequest request)
          Expose the tool attributes, according to corresponding bean property settings.
protected  java.lang.String getEncoding()
          Return the encoding for the Velocity template.
protected  org.apache.velocity.Template getTemplate()
          Retrieve the Velocity template to be rendered by this view.
protected  org.apache.velocity.Template getTemplate(java.lang.String name)
          Retrieve the Velocity template specified by the given name, using the encoding specified by the "encoding" bean property.
protected  org.apache.velocity.app.VelocityEngine getVelocityEngine()
          Return the VelocityEngine used by this view.
protected  void initApplicationContext()
          Invoked on startup.
protected  void initTool(java.lang.Object tool, org.apache.velocity.context.Context velocityContext)
          Initialize the given tool instance.
protected  boolean isCacheTemplate()
          Return whether the Velocity template should be cached.
protected  void mergeTemplate(org.apache.velocity.Template template, org.apache.velocity.context.Context context, javax.servlet.http.HttpServletResponse response)
          Merge the template with the context.
protected  void renderMergedTemplateModel(java.util.Map<java.lang.String,java.lang.Object> model, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
          Process the model map by merging it with the Velocity template.
 void setCacheTemplate(boolean cacheTemplate)
          Set whether the Velocity template should be cached.
 void setDateToolAttribute(java.lang.String dateToolAttribute)
          Set the name of the DateTool helper object to expose in the Velocity context of this view, or null if not needed.
 void setEncoding(java.lang.String encoding)
          Set the encoding of the Velocity template file.
 void setNumberToolAttribute(java.lang.String numberToolAttribute)
          Set the name of the NumberTool helper object to expose in the Velocity context of this view, or null if not needed.
 void setToolAttributes(java.util.Map<java.lang.String,java.lang.Class> toolAttributes)
          Set tool attributes to expose to the view, as attribute name / class name pairs.
 void setVelocityEngine(org.apache.velocity.app.VelocityEngine velocityEngine)
          Set the VelocityEngine to be used by this view.
 
Methods inherited from class org.springframework.web.servlet.view.AbstractTemplateView
applyContentType, renderMergedOutputModel, setAllowRequestOverride, setAllowSessionOverride, setExposeRequestAttributes, setExposeSessionAttributes, setExposeSpringMacroHelpers
 
Methods inherited from class org.springframework.web.servlet.view.AbstractUrlBasedView
afterPropertiesSet, getUrl, isUrlRequired, setUrl, toString
 
Methods inherited from class org.springframework.web.servlet.view.AbstractView
addStaticAttribute, createRequestContext, createTemporaryOutputStream, exposeModelAsRequestAttributes, generatesDownloadContent, getAttributesMap, getBeanName, getContentType, getRequestContextAttribute, getStaticAttributes, prepareResponse, render, setAttributes, setAttributesCSV, setAttributesMap, setBeanName, setContentType, setRequestContextAttribute, writeToResponse
 
Methods inherited from class org.springframework.web.context.support.WebApplicationObjectSupport
getServletContext, getTempDir, getWebApplicationContext, initApplicationContext, initServletContext, isContextRequired, setServletContext
 
Methods inherited from class org.springframework.context.support.ApplicationObjectSupport
getApplicationContext, getMessageSourceAccessor, requiredContextClass, setApplicationContext
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

VelocityView

public VelocityView()
Method Detail

setToolAttributes

public void setToolAttributes(java.util.Map<java.lang.String,java.lang.Class> toolAttributes)
Set tool attributes to expose to the view, as attribute name / class name pairs. An instance of the given class will be added to the Velocity context for each rendering operation, under the given attribute name.

For example, an instance of MathTool, which is part of the generic package of Velocity Tools, can be bound under the attribute name "math", specifying the fully qualified class name "org.apache.velocity.tools.generic.MathTool" as value.

Note that VelocityView can only create simple generic tools or values, that is, classes with a public default constructor and no further initialization needs. This class does not do any further checks, to not introduce a required dependency on a specific tools package.

For tools that are part of the view package of Velocity Tools, a special Velocity context and a special init callback are needed. Use VelocityToolboxView in such a case, or override createVelocityContext and initTool accordingly.

For a simple VelocityFormatter instance or special locale-aware instances of DateTool/NumberTool, which are part of the generic package of Velocity Tools, specify the "velocityFormatterAttribute", "dateToolAttribute" or "numberToolAttribute" properties, respectively.

Parameters:
toolAttributes - attribute names as keys, and tool class names as values
See Also:
MathTool, VelocityToolboxView, createVelocityContext(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse), initTool(java.lang.Object, org.apache.velocity.context.Context), setDateToolAttribute(java.lang.String), setNumberToolAttribute(java.lang.String)

setDateToolAttribute

public void setDateToolAttribute(java.lang.String dateToolAttribute)
Set the name of the DateTool helper object to expose in the Velocity context of this view, or null if not needed. The exposed DateTool will be aware of the current locale, as determined by Spring's LocaleResolver.

DateTool is part of the generic package of Velocity Tools 1.0. Spring uses a special locale-aware subclass of DateTool.

See Also:
DateTool, RequestContextUtils.getLocale(javax.servlet.http.HttpServletRequest), LocaleResolver

setNumberToolAttribute

public void setNumberToolAttribute(java.lang.String numberToolAttribute)
Set the name of the NumberTool helper object to expose in the Velocity context of this view, or null if not needed. The exposed NumberTool will be aware of the current locale, as determined by Spring's LocaleResolver.

NumberTool is part of the generic package of Velocity Tools 1.1. Spring uses a special locale-aware subclass of NumberTool.

See Also:
NumberTool, RequestContextUtils.getLocale(javax.servlet.http.HttpServletRequest), LocaleResolver

setEncoding

public void setEncoding(java.lang.String encoding)
Set the encoding of the Velocity template file. Default is determined by the VelocityEngine: "ISO-8859-1" if not specified otherwise.

Specify the encoding in the VelocityEngine rather than per template if all your templates share a common encoding.


getEncoding

protected java.lang.String getEncoding()
Return the encoding for the Velocity template.


setCacheTemplate

public void setCacheTemplate(boolean cacheTemplate)
Set whether the Velocity template should be cached. Default is "false". It should normally be true in production, but setting this to false enables us to modify Velocity templates without restarting the application (similar to JSPs).

Note that this is a minor optimization only, as Velocity itself caches templates in a modification-aware fashion.


isCacheTemplate

protected boolean isCacheTemplate()
Return whether the Velocity template should be cached.


setVelocityEngine

public void setVelocityEngine(org.apache.velocity.app.VelocityEngine velocityEngine)
Set the VelocityEngine to be used by this view. If this is not set, the default lookup will occur: A single VelocityConfig is expected in the current web application context, with any bean name.

See Also:
VelocityConfig

getVelocityEngine

protected org.apache.velocity.app.VelocityEngine getVelocityEngine()
Return the VelocityEngine used by this view.


initApplicationContext

protected void initApplicationContext()
                               throws BeansException
Invoked on startup. Looks for a single VelocityConfig bean to find the relevant VelocityEngine for this factory.

Overrides:
initApplicationContext in class ApplicationObjectSupport
Throws:
ApplicationContextException - in case of initialization errors
BeansException - if thrown by ApplicationContext methods
See Also:
ApplicationObjectSupport.setApplicationContext(org.springframework.context.ApplicationContext)

autodetectVelocityEngine

protected org.apache.velocity.app.VelocityEngine autodetectVelocityEngine()
                                                                   throws BeansException
Autodetect a VelocityEngine via the ApplicationContext. Called if no explicit VelocityEngine has been specified.

Returns:
the VelocityEngine to use for VelocityViews
Throws:
BeansException - if no VelocityEngine could be found
See Also:
ApplicationObjectSupport.getApplicationContext(), setVelocityEngine(org.apache.velocity.app.VelocityEngine)

checkTemplate

protected void checkTemplate()
                      throws ApplicationContextException
Check that the Velocity template used for this view exists and is valid.

Can be overridden to customize the behavior, for example in case of multiple templates to be rendered into a single view.

Throws:
ApplicationContextException - if the template cannot be found or is invalid

renderMergedTemplateModel

protected void renderMergedTemplateModel(java.util.Map<java.lang.String,java.lang.Object> model,
                                         javax.servlet.http.HttpServletRequest request,
                                         javax.servlet.http.HttpServletResponse response)
                                  throws java.lang.Exception
Process the model map by merging it with the Velocity template. Output is directed to the servlet response.

This method can be overridden if custom behavior is needed.

Specified by:
renderMergedTemplateModel in class AbstractTemplateView
Parameters:
model - combined output Map, with request attributes and session attributes merged into it if required
request - current HTTP request
response - current HTTP response
Throws:
java.lang.Exception - if rendering failed

exposeHelpers

protected void exposeHelpers(java.util.Map<java.lang.String,java.lang.Object> model,
                             javax.servlet.http.HttpServletRequest request)
                      throws java.lang.Exception
Expose helpers unique to each rendering operation. This is necessary so that different rendering operations can't overwrite each other's formats etc.

Called by renderMergedTemplateModel. The default implementation is empty. This method can be overridden to add custom helpers to the model.

Parameters:
model - the model that will be passed to the template for merging
request - current HTTP request
Throws:
java.lang.Exception - if there's a fatal error while we're adding model attributes
See Also:
renderMergedTemplateModel(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)

createVelocityContext

protected org.apache.velocity.context.Context createVelocityContext(java.util.Map<java.lang.String,java.lang.Object> model,
                                                                    javax.servlet.http.HttpServletRequest request,
                                                                    javax.servlet.http.HttpServletResponse response)
                                                             throws java.lang.Exception
Create a Velocity Context instance for the given model, to be passed to the template for merging.

The default implementation delegates to createVelocityContext(Map). Can be overridden for a special context class, for example ChainedContext which is part of the view package of Velocity Tools. ChainedContext is needed for initialization of ViewTool instances.

Have a look at VelocityToolboxView, which pre-implements ChainedContext support. This is not part of the standard VelocityView class in order to avoid a required dependency on the view package of Velocity Tools.

Parameters:
model - the model Map, containing the model attributes to be exposed to the view
request - current HTTP request
response - current HTTP response
Returns:
the Velocity Context
Throws:
java.lang.Exception - if there's a fatal error while creating the context
See Also:
createVelocityContext(Map), initTool(java.lang.Object, org.apache.velocity.context.Context), ChainedContext, VelocityToolboxView

createVelocityContext

protected org.apache.velocity.context.Context createVelocityContext(java.util.Map<java.lang.String,java.lang.Object> model)
                                                             throws java.lang.Exception
Create a Velocity Context instance for the given model, to be passed to the template for merging.

Default implementation creates an instance of Velocity's VelocityContext implementation class.

Parameters:
model - the model Map, containing the model attributes to be exposed to the view
Returns:
the Velocity Context
Throws:
java.lang.Exception - if there's a fatal error while creating the context
See Also:
VelocityContext

exposeHelpers

protected void exposeHelpers(org.apache.velocity.context.Context velocityContext,
                             javax.servlet.http.HttpServletRequest request,
                             javax.servlet.http.HttpServletResponse response)
                      throws java.lang.Exception
Expose helpers unique to each rendering operation. This is necessary so that different rendering operations can't overwrite each other's formats etc.

Called by renderMergedTemplateModel. Default implementation delegates to exposeHelpers(velocityContext, request). This method can be overridden to add special tools to the context, needing the servlet response to initialize (see Velocity Tools, for example LinkTool and ViewTool/ChainedContext).

Parameters:
velocityContext - Velocity context that will be passed to the template
request - current HTTP request
response - current HTTP response
Throws:
java.lang.Exception - if there's a fatal error while we're adding model attributes
See Also:
exposeHelpers(org.apache.velocity.context.Context, HttpServletRequest)

exposeHelpers

protected void exposeHelpers(org.apache.velocity.context.Context velocityContext,
                             javax.servlet.http.HttpServletRequest request)
                      throws java.lang.Exception
Expose helpers unique to each rendering operation. This is necessary so that different rendering operations can't overwrite each other's formats etc.

Default implementation is empty. This method can be overridden to add custom helpers to the Velocity context.

Parameters:
velocityContext - Velocity context that will be passed to the template
request - current HTTP request
Throws:
java.lang.Exception - if there's a fatal error while we're adding model attributes
See Also:
exposeHelpers(Map, HttpServletRequest)

exposeToolAttributes

protected void exposeToolAttributes(org.apache.velocity.context.Context velocityContext,
                                    javax.servlet.http.HttpServletRequest request)
                             throws java.lang.Exception
Expose the tool attributes, according to corresponding bean property settings.

Do not override this method unless for further tools driven by bean properties. Override one of the exposeHelpers methods to add custom helpers.

Parameters:
velocityContext - Velocity context that will be passed to the template
request - current HTTP request
Throws:
java.lang.Exception - if there's a fatal error while we're adding model attributes
See Also:
setDateToolAttribute(java.lang.String), setNumberToolAttribute(java.lang.String), exposeHelpers(Map, HttpServletRequest), exposeHelpers(org.apache.velocity.context.Context, HttpServletRequest, HttpServletResponse)

initTool

protected void initTool(java.lang.Object tool,
                        org.apache.velocity.context.Context velocityContext)
                 throws java.lang.Exception
Initialize the given tool instance. The default implementation is empty.

Can be overridden to check for special callback interfaces, for example the ViewContext interface which is part of the view package of Velocity Tools. In the particular case of ViewContext, you'll usually also need a special Velocity context, like ChainedContext which is part of Velocity Tools too.

Have a look at VelocityToolboxView, which pre-implements such a ViewTool check. This is not part of the standard VelocityView class in order to avoid a required dependency on the view package of Velocity Tools.

Parameters:
tool - the tool instance to initialize
velocityContext - the Velocity context
Throws:
java.lang.Exception - if initializion of the tool failed
See Also:
createVelocityContext(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse), ViewContext, ChainedContext, VelocityToolboxView

doRender

protected void doRender(org.apache.velocity.context.Context context,
                        javax.servlet.http.HttpServletResponse response)
                 throws java.lang.Exception
Render the Velocity view to the given response, using the given Velocity context which contains the complete template model to use.

The default implementation renders the template specified by the "url" bean property, retrieved via getTemplate. It delegates to the mergeTemplate method to merge the template instance with the given Velocity context.

Can be overridden to customize the behavior, for example to render multiple templates into a single view.

Parameters:
context - the Velocity context to use for rendering
response - servlet response (use this to get the OutputStream or Writer)
Throws:
java.lang.Exception - if thrown by Velocity
See Also:
AbstractUrlBasedView.setUrl(java.lang.String), getTemplate(), mergeTemplate(org.apache.velocity.Template, org.apache.velocity.context.Context, javax.servlet.http.HttpServletResponse)

getTemplate

protected org.apache.velocity.Template getTemplate()
                                            throws java.lang.Exception
Retrieve the Velocity template to be rendered by this view.

By default, the template specified by the "url" bean property will be retrieved: either returning a cached template instance or loading a fresh instance (according to the "cacheTemplate" bean property)

Returns:
the Velocity template to render
Throws:
java.lang.Exception - if thrown by Velocity
See Also:
AbstractUrlBasedView.setUrl(java.lang.String), setCacheTemplate(boolean), getTemplate(String)

getTemplate

protected org.apache.velocity.Template getTemplate(java.lang.String name)
                                            throws java.lang.Exception
Retrieve the Velocity template specified by the given name, using the encoding specified by the "encoding" bean property.

Can be called by subclasses to retrieve a specific template, for example to render multiple templates into a single view.

Parameters:
name - the file name of the desired template
Returns:
the Velocity template
Throws:
java.lang.Exception - if thrown by Velocity
See Also:
VelocityEngine.getTemplate(java.lang.String)

mergeTemplate

protected void mergeTemplate(org.apache.velocity.Template template,
                             org.apache.velocity.context.Context context,
                             javax.servlet.http.HttpServletResponse response)
                      throws java.lang.Exception
Merge the template with the context. Can be overridden to customize the behavior.

Parameters:
template - the template to merge
context - the Velocity context to use for rendering
response - servlet response (use this to get the OutputStream or Writer)
Throws:
java.lang.Exception - if thrown by Velocity
See Also:
Template.merge(org.apache.velocity.context.Context, java.io.Writer)