Package org.springframework.web.servlet.view.freemarker

# Class FreeMarkerView

java.lang.Object
org.springframework.context.support.ApplicationObjectSupport
org.springframework.web.context.support.WebApplicationObjectSupport
org.springframework.web.servlet.view.AbstractView
org.springframework.web.servlet.view.AbstractUrlBasedView
org.springframework.web.servlet.view.AbstractTemplateView
org.springframework.web.servlet.view.freemarker.FreeMarkerView

All Implemented Interfaces:
  `org.springframework.beans.factory.Aware`, `org.springframework.beans.factory.BeanNameAware`, `org.springframework.beans.factory.InitializingBean`, `org.springframework.context.ApplicationContextAware`, `org.springframework.web.context.ServletContextAware`, `View`

public class FreeMarkerView extends AbstractTemplateView
View using the FreeMarker template engine.

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 FreeMarker `Configuration`.
- `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(freemarker.template.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, as of Spring Framework 6.2, it is no longer 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:
  - `AbstractUrlBasedView.setUrl(java.lang.String)`
  - `AbstractTemplateView.setExposeSpringMacroHelpers(boolean)`
  - `setEncoding(java.lang.String)`
  - `setConfiguration(freemarker.template.Configuration)`
  - `FreeMarkerConfig`
  - `FreeMarkerConfigurer`

## 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`

### Fields inherited from interface org.springframework.web.servlet.View

`PATH_VARIABLES, RESPONSE_STATUS_ATTRIBUTE, SELECTED_CONTENT_TYPE`

## Constructor Summary

Constructors
Constructor
Description
`FreeMarkerView()`

## Method Summary

Modifier and Type
Method
Description
`protected FreeMarkerConfig`
`autodetectConfiguration()`
Autodetect a `FreeMarkerConfig` object via the `ApplicationContext`.
`protected freemarker.template.SimpleHash`
`buildTemplateModel(Map<String,Object> model, HttpServletRequest request, HttpServletResponse response)`
Build a FreeMarker template model for the given model Map.
`boolean`
`checkResource(Locale locale)`
Check that the FreeMarker template used for this view exists and is valid.
`protected void`
`doRender(Map<String,Object> model, HttpServletRequest request, HttpServletResponse response)`
Render the FreeMarker view to the given response, using the given model map which contains the complete template model to use.
`protected void`
`exposeHelpers(Map<String,Object> model, HttpServletRequest request)`
Expose helpers unique to each rendering operation.
`protected freemarker.template.Configuration`
`getConfiguration()`
Return the FreeMarker `Configuration` used by this view.
`protected String`
`getEncoding()`
Get the encoding used to decode byte sequences to character sequences when reading the FreeMarker template file for this view, or `null` to signal that the FreeMarker `Configuration` should be used to determine the encoding.
`protected freemarker.template.ObjectWrapper`
`getObjectWrapper()`
Return the configured FreeMarker `ObjectWrapper`, or a default wrapper if none specified.
`protected freemarker.template.Template`
`getTemplate(String name, Locale locale)`
Retrieve the FreeMarker `Template` to be rendered by this view, for the specified name and locale and using the configured encoding if set.
`protected freemarker.template.Template`
`getTemplate(Locale locale)`
Retrieve the FreeMarker `Template` to be rendered by this view, for the specified locale and using the configured encoding if set.
`protected void`
`initServletContext(ServletContext servletContext)`
Invoked on startup.
`protected freemarker.template.Configuration`
`obtainConfiguration()`
Obtain the FreeMarker `Configuration` for actual use.
`protected void`
`processTemplate(freemarker.template.Template template, freemarker.template.SimpleHash model, HttpServletResponse response)`
Process the FreeMarker template and write the result to the response.
`protected void`
`renderMergedTemplateModel(Map<String,Object> model, HttpServletRequest request, HttpServletResponse response)`
Process the model map by merging it with the FreeMarker template.
`void`
`setCharset(Charset charset)`
Set the `Charset` used to decode byte sequences to character sequences when reading the FreeMarker template file for this view.
`void`
`setConfiguration(freemarker.template.Configuration configuration)`
Set the FreeMarker `Configuration` to be used by this view.
`void`
`setEncoding(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 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, 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, writeToResponse`

### 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, obtainApplicationContext, requiredContextClass, setApplicationContext`

### Methods inherited from class java.lang.Object

`clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait`

## Constructor Details

### FreeMarkerView

public FreeMarkerView()

## Method Details

### setEncoding

public void setEncoding(@Nullable String encoding)
Set the encoding used to decode byte sequences to character sequences when reading the FreeMarker template file for this view.

Defaults to `null` to signal that the FreeMarker `Configuration` should 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 property `file.encoding`) or UTF-8 if the platform file encoding is undefined.

It's recommended to specify the encoding in the FreeMarker `Configuration` rather 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:
  - `Configuration.setDefaultEncoding(java.lang.String)`
  - `setCharset(Charset)`
  - `getEncoding()`
  - `AbstractView.setContentType(String)`

### setCharset

public void setCharset(@Nullable Charset charset)
Set the `Charset` used 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:
  - `StandardCharsets`

### getEncoding

@Nullable protected String getEncoding()
Get the encoding used to decode byte sequences to character sequences when reading the FreeMarker template file for this view, or `null` to signal that the FreeMarker `Configuration` should be used to determine the encoding.

See Also:
  - `setEncoding(String)`

### setConfiguration

public void setConfiguration(@Nullable freemarker.template.Configuration configuration)
Set the FreeMarker `Configuration` to be used by this view.

If not set, the default lookup will occur: a single `FreeMarkerConfig` is expected in the current web application context, with any bean name. Note: using this method will cause a new instance of `TaglibFactory` to created for every single `FreeMarkerView` instance. This can be quite expensive in terms of memory and initial CPU usage. In production, it is recommended that you use a `FreeMarkerConfig` which exposes a single shared `TaglibFactory`.

### getConfiguration

@Nullable protected freemarker.template.Configuration getConfiguration()
Return the FreeMarker `Configuration` used by this view.

### obtainConfiguration

protected freemarker.template.Configuration obtainConfiguration()
Obtain the FreeMarker `Configuration` for actual use.

Returns:
  the FreeMarker configuration (never `null`)
Throws:
  `IllegalStateException` - in case of no Configuration object set
Since:
  5.0

### initServletContext

protected void initServletContext(ServletContext servletContext) throws org.springframework.beans.BeansException
Invoked on startup. Looks for a single `FreeMarkerConfig` bean to find the relevant `Configuration` for 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:
  `initServletContext` in class `org.springframework.web.context.support.WebApplicationObjectSupport`
Throws:
  `org.springframework.beans.BeansException`
See Also:
  - `TemplateCache.getTemplate(java.lang.String, java.util.Locale, java.lang.Object, java.lang.String, boolean)`

### autodetectConfiguration

protected FreeMarkerConfig autodetectConfiguration() throws org.springframework.beans.BeansException
Autodetect a `FreeMarkerConfig` object via the `ApplicationContext`.

Returns:
  the `FreeMarkerConfig` instance to use for FreeMarkerViews
Throws:
  `org.springframework.beans.BeansException` - if no `FreeMarkerConfig` bean could be found
See Also:
  - `ApplicationObjectSupport.getApplicationContext()`
  - `setConfiguration(freemarker.template.Configuration)`

### getObjectWrapper

protected freemarker.template.ObjectWrapper getObjectWrapper()
Return the configured FreeMarker `ObjectWrapper`, or a default wrapper if none specified.

See Also:
  - `Configurable.getObjectWrapper()`

### checkResource

public boolean checkResource(Locale locale) throws Exception
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:
  `checkResource` in class `AbstractUrlBasedView`
Parameters:
  `locale` - the desired Locale that we're looking for
Returns:
  `true` if the resource exists (or is assumed to exist); `false` if 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, HttpServletRequest request, HttpServletResponse response) throws Exception
Process 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:
  `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:
  `Exception` - if rendering failed

### exposeHelpers

protected void exposeHelpers(Map<String,Object> model, HttpServletRequest request) throws 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 at merge time
  `request` - current HTTP request
Throws:
  `Exception` - if there's a fatal error while we're adding information to the context
See Also:
  - `renderMergedTemplateModel(java.util.Map<java.lang.String, java.lang.Object>, jakarta.servlet.http.HttpServletRequest, jakarta.servlet.http.HttpServletResponse)`

### doRender

protected void doRender(Map<String,Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception
Render 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 the `processTemplate` method 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 rendering
  `request` - current HTTP request
  `response` - current servlet response
Throws:
  `IOException` - if the template file could not be retrieved
  `Exception` - if rendering failed
See Also:
  - `AbstractUrlBasedView.setUrl(java.lang.String)`
  - `RequestContextUtils.getLocale(jakarta.servlet.http.HttpServletRequest)`
  - `getTemplate(java.util.Locale)`
  - `processTemplate(freemarker.template.Template, freemarker.template.SimpleHash, jakarta.servlet.http.HttpServletResponse)`
  - `FreemarkerServlet`

### buildTemplateModel

protected freemarker.template.SimpleHash buildTemplateModel(Map<String,Object> model, HttpServletRequest request, 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 rendering
  `request` - current HTTP request
  `response` - current servlet response
Returns:
  the FreeMarker template model, as a `SimpleHash` or subclass thereof

### getTemplate

protected freemarker.template.Template getTemplate(Locale locale) throws IOException
Retrieve the FreeMarker `Template` to 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 `Template` to render
Throws:
  `IOException` - if the template file could not be retrieved
See Also:
  - `AbstractUrlBasedView.setUrl(java.lang.String)`
  - `getTemplate(String, java.util.Locale)`

### getTemplate

protected freemarker.template.Template getTemplate(String name, Locale locale) throws IOException
Retrieve the FreeMarker `Template` to 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 template
  `locale` - the current locale
Returns:
  the FreeMarker template
Throws:
  `IOException` - if the template file could not be retrieved
See Also:
  - `setEncoding(String)`

### processTemplate

protected void processTemplate(freemarker.template.Template template, freemarker.template.SimpleHash model, 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 `Environment` to the character encoding of the supplied `HttpServletResponse`.

Can be overridden to customize the behavior.

Parameters:
  `template` - the template to process
  `model` - the model for the template
  `response` - servlet response (use this to get the OutputStream or Writer)
Throws:
  `IOException` - if the template file could not be retrieved
  `freemarker.template.TemplateException` - if thrown by FreeMarker
See Also:
  - `Template.createProcessingEnvironment(Object, java.io.Writer)`
  - `Environment.process()`