Class FreeMarkerView
- All Implemented Interfaces:
Aware, BeanNameAware, InitializingBean, ApplicationContextAware, ServletContextAware, View
Exposes the following configuration properties:
url: the location of the FreeMarker template relative to the FreeMarker template context (directory).encoding: the encoding used to decode byte sequences to character sequences when reading the FreeMarker template file. Default is determined by the FreeMarkerConfiguration.contentType: the content type of the rendered response. Defaults to"text/html;charset=ISO-8859-1"but may need to be set to a value that corresponds to the actual generated content type (see note below).
Depends on a single FreeMarkerConfig object such as
FreeMarkerConfigurer being accessible in the current web application
context. Alternatively the FreeMarker Configuration can be set directly
via setConfiguration(Configuration).
Note: To ensure that the correct encoding is used when rendering the
response, set the content type with an
appropriate charset attribute — for example,
"text/html;charset=UTF-8". When using FreeMarkerViewResolver
to create the view for you, set the
content type
directly in the FreeMarkerViewResolver; however, it is not necessary to
explicitly set the content type in the FreeMarkerViewResolver if you have
set an explicit encoding via either setEncoding(String),
FreeMarkerConfigurationFactory.setDefaultEncoding(String), or
Configuration.setDefaultEncoding(String).
Note: Spring's FreeMarker support requires FreeMarker 2.3.33 or higher.
- Since:
- 03.03.2004
- Author:
- Darren Davison, Juergen Hoeller, Sam Brannen
- See Also:
-
Field Summary
Fields inherited from class AbstractTemplateView
SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTEFields inherited from class AbstractView
DEFAULT_CONTENT_TYPEFields inherited from class ApplicationObjectSupport
loggerFields inherited from interface View
PATH_VARIABLES, RESPONSE_STATUS_ATTRIBUTE, SELECTED_CONTENT_TYPE -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected FreeMarkerConfigAutodetect aFreeMarkerConfigobject via theApplicationContext.protected freemarker.template.SimpleHashbuildTemplateModel(Map<String, Object> model, jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) Build a FreeMarker template model for the given model Map.booleancheckResource(Locale locale) Check that the FreeMarker template used for this view exists and is valid.protected voiddoRender(Map<String, Object> model, jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) Render the FreeMarker view to the given response, using the given model map which contains the complete template model to use.protected voidexposeHelpers(Map<String, Object> model, jakarta.servlet.http.HttpServletRequest request) Expose helpers unique to each rendering operation.protected @Nullable freemarker.template.ConfigurationReturn the FreeMarkerConfigurationused by this view.Get the encoding used to decode byte sequences to character sequences when reading the FreeMarker template file for this view, ornullto signal that the FreeMarkerConfigurationshould be used to determine the encoding.protected freemarker.template.ObjectWrapperReturn the configured FreeMarkerObjectWrapper, or a default wrapper if none specified.protected freemarker.template.TemplategetTemplate(String name, Locale locale) Retrieve the FreeMarkerTemplateto be rendered by this view, for the specified name and locale and using the configured encoding if set.protected freemarker.template.TemplategetTemplate(Locale locale) Retrieve the FreeMarkerTemplateto be rendered by this view, for the specified locale and using the configured encoding if set.protected voidinitServletContext(jakarta.servlet.ServletContext servletContext) Invoked on startup.protected freemarker.template.ConfigurationObtain the FreeMarkerConfigurationfor actual use.protected voidprocessTemplate(freemarker.template.Template template, freemarker.template.SimpleHash model, jakarta.servlet.http.HttpServletResponse response) Process the FreeMarker template and write the result to the response.protected voidrenderMergedTemplateModel(Map<String, Object> model, jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) Process the model map by merging it with the FreeMarker template.voidsetCharset(@Nullable Charset charset) Set theCharsetused to decode byte sequences to character sequences when reading the FreeMarker template file for this view.voidsetConfiguration(@Nullable freemarker.template.Configuration configuration) Set the FreeMarkerConfigurationto be used by this view.voidsetEncoding(@Nullable String encoding) Set the encoding used to decode byte sequences to character sequences when reading the FreeMarker template file for this view.Methods inherited from class AbstractTemplateView
applyContentType, renderMergedOutputModel, setAllowRequestOverride, setAllowSessionOverride, setExposeRequestAttributes, setExposeSessionAttributes, setExposeSpringMacroHelpersMethods inherited from class AbstractUrlBasedView
afterPropertiesSet, getUrl, isUrlRequired, setUrl, toStringMethods inherited from class AbstractView
addStaticAttribute, createMergedOutputModel, createRequestContext, createTemporaryOutputStream, exposeModelAsRequestAttributes, formatViewName, generatesDownloadContent, getAttributesMap, getBeanName, getContentType, getRequestContextAttribute, getRequestToExpose, getStaticAttributes, isExposePathVariables, prepareResponse, render, setAttributes, setAttributesCSV, setAttributesMap, setBeanName, setContentType, setExposeContextBeansAsAttributes, setExposedContextBeanNames, setExposePathVariables, setRequestContextAttribute, setResponseContentType, writeToResponseMethods inherited from class WebApplicationObjectSupport
getServletContext, getTempDir, getWebApplicationContext, initApplicationContext, isContextRequired, setServletContextMethods inherited from class ApplicationObjectSupport
getApplicationContext, getMessageSourceAccessor, initApplicationContext, obtainApplicationContext, requiredContextClass, setApplicationContext
-
Constructor Details
-
FreeMarkerView
public FreeMarkerView()
-
-
Method Details
-
setEncoding
Set the encoding used to decode byte sequences to character sequences when reading the FreeMarker template file for this view.Defaults to
nullto signal that the FreeMarkerConfigurationshould be used to determine the encoding.A non-null encoding will override the default encoding determined by the FreeMarker
Configuration.If the encoding is not explicitly set here or in the FreeMarker
Configuration, FreeMarker will read template files using the platform file encoding (defined by the JVM system propertyfile.encoding) or UTF-8 if the platform file encoding is undefined.It's recommended to specify the encoding in the FreeMarker
Configurationrather than per template if all your templates share a common encoding.See the note in the class-level documentation for details regarding the encoding used to render the response.
- See Also:
-
setCharset
Set theCharsetused to decode byte sequences to character sequences when reading the FreeMarker template file for this view.See
setEncoding(String)for details.- Since:
- 6.2
- See Also:
-
getEncoding
-
setConfiguration
Set the FreeMarkerConfigurationto be used by this view.If not set, the default lookup will occur: a single
FreeMarkerConfigis expected in the current web application context, with any bean name. Note: using this method will cause a new instance ofTaglibFactoryto created for every singleFreeMarkerViewinstance. This can be quite expensive in terms of memory and initial CPU usage. In production, it is recommended that you use aFreeMarkerConfigwhich exposes a single sharedTaglibFactory. -
getConfiguration
Return the FreeMarkerConfigurationused by this view. -
obtainConfiguration
protected freemarker.template.Configuration obtainConfiguration()Obtain the FreeMarkerConfigurationfor actual use.- Returns:
- the FreeMarker configuration (never
null) - Throws:
IllegalStateException- in case of no Configuration object set- Since:
- 5.0
-
initServletContext
protected void initServletContext(jakarta.servlet.ServletContext servletContext) throws BeansException Invoked on startup. Looks for a singleFreeMarkerConfigbean to find the relevantConfigurationfor this view.Checks that the template for the default Locale can be found: FreeMarker will check non-Locale-specific templates if a locale-specific one is not found.
- Overrides:
initServletContextin classWebApplicationObjectSupport- Parameters:
servletContext- the ServletContext that this application object runs in (nevernull)- Throws:
BeansException- See Also:
-
autodetectConfiguration
Autodetect aFreeMarkerConfigobject via theApplicationContext.- Returns:
- the
FreeMarkerConfiginstance to use for FreeMarkerViews - Throws:
BeansException- if noFreeMarkerConfigbean could be found- See Also:
-
getObjectWrapper
protected freemarker.template.ObjectWrapper getObjectWrapper()Return the configured FreeMarkerObjectWrapper, or a default wrapper if none specified.- See Also:
-
checkResource
Check that the FreeMarker 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.
- Overrides:
checkResourcein classAbstractUrlBasedView- Parameters:
locale- the desired Locale that we're looking for- Returns:
trueif the resource exists (or is assumed to exist);falseif we know that it does not exist- Throws:
Exception- if the resource exists but is invalid (for example, could not be parsed)
-
renderMergedTemplateModel
protected void renderMergedTemplateModel(Map<String, Object> model, jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) throws ExceptionProcess the model map by merging it with the FreeMarker template.Output is directed to the servlet response.
This method can be overridden if custom behavior is needed.
- Specified by:
renderMergedTemplateModelin classAbstractTemplateView- Parameters:
model- combined output Map, with request attributes and session attributes merged into it if requiredrequest- current HTTP requestresponse- current HTTP response- Throws:
Exception- if rendering failed
-
exposeHelpers
protected void exposeHelpers(Map<String, Object> model, jakarta.servlet.http.HttpServletRequest request) throws ExceptionExpose 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 at merge timerequest- current HTTP request- Throws:
Exception- if there's a fatal error while we're adding information to the context- See Also:
-
doRender
protected void doRender(Map<String, Object> model, jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) throws ExceptionRender the FreeMarker view to the given response, using the given model map 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 theprocessTemplatemethod to merge the template instance with the given template model.Adds the standard Freemarker hash models to the model: request parameters, request, session and application (ServletContext), as well as the JSP tag library hash model.
Can be overridden to customize the behavior, for example to render multiple templates into a single view.
- Parameters:
model- the model to use for renderingrequest- current HTTP requestresponse- current servlet response- Throws:
IOException- if the template file could not be retrievedException- if rendering failed- See Also:
-
buildTemplateModel
protected freemarker.template.SimpleHash buildTemplateModel(Map<String, Object> model, jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) Build a FreeMarker template model for the given model Map.The default implementation builds a
AllHttpScopesHashModel.- Parameters:
model- the model to use for renderingrequest- current HTTP requestresponse- current servlet response- Returns:
- the FreeMarker template model, as a
SimpleHashor subclass thereof
-
getTemplate
Retrieve the FreeMarkerTemplateto be rendered by this view, for the specified locale and using the configured encoding if set.By default, the template specified by the "url" bean property will be retrieved.
- Parameters:
locale- the current locale- Returns:
- the FreeMarker
Templateto render - Throws:
IOException- if the template file could not be retrieved- See Also:
-
getTemplate
Retrieve the FreeMarkerTemplateto be rendered by this view, for the specified name and locale and using the configured encoding if set.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 templatelocale- the current locale- Returns:
- the FreeMarker template
- Throws:
IOException- if the template file could not be retrieved- See Also:
-
processTemplate
protected void processTemplate(freemarker.template.Template template, freemarker.template.SimpleHash model, jakarta.servlet.http.HttpServletResponse response) throws IOException, freemarker.template.TemplateException Process the FreeMarker template and write the result to the response.As of Spring Framework 6.2, this method sets the output encoding of the FreeMarker
Environmentto the character encoding of the suppliedHttpServletResponse.Can be overridden to customize the behavior.
- Parameters:
template- the template to processmodel- the model for the templateresponse- servlet response (use this to get the OutputStream or Writer)- Throws:
IOException- if the template file could not be retrievedfreemarker.template.TemplateException- if thrown by FreeMarker- See Also:
-