Class FreeMarkerView
- All Implemented Interfaces:
Aware, BeanNameAware, InitializingBean, ApplicationContextAware, View
View implementation that uses the FreeMarker template engine.
Exposes the following configuration properties:
url: the location of the FreeMarker template relative to the FreeMarkerConfigurer'stemplateLoaderPath.encoding: the encoding used to decode byte sequences to character sequences when reading the FreeMarker template file. Default is determined by the FreeMarkerConfiguration.
Depends on a single FreeMarkerConfig object such as
FreeMarkerConfigurer being accessible in the 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 as well as when the client reads the response, the following steps must be taken.
- Either set the default encoding in the FreeMarker
Configurationor set the encoding for this view. - Configure the supported media type with a
charsetequal to the configuredencodingviaAbstractView.setSupportedMediaTypes(java.util.List)orViewResolverSupport.setSupportedMediaTypes(java.util.List).
FreeMarkerConfigurer sets the default encoding in
the FreeMarker Configuration to "UTF-8" and that
AbstractView
sets the supported media type to "text/html;charset=UTF-8" by default.
Thus, those default values are likely suitable for most applications.
Note: Spring's FreeMarker support requires FreeMarker 2.3.33 or higher.
- Since:
- 5.0
- Author:
- Rossen Stoyanchev, Sam Brannen
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringAttribute name of theRequestContextinstance in the template model, available to Spring's macros — for example, for creatingBindStatusobjects.Fields inherited from class AbstractView
logger, REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAMEFields inherited from interface View
BINDING_CONTEXT_ATTRIBUTE -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidInvoked by the containingBeanFactoryafter it has set all bean properties and satisfiedBeanFactoryAware,ApplicationContextAwareetc.protected FreeMarkerConfigAutodetect aFreeMarkerConfigobject in theApplicationContext.booleancheckResourceExists(Locale locale) Check that the FreeMarker template used for this view exists and is valid.protected @nullable freemarker.template.ConfigurationGet 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.getModelAttributes(@nullable Map<String, ?> model, ServerWebExchange exchange) Prepare the model to use for rendering by potentially exposing aRequestContextfor use in Spring FreeMarker macros and then delegating to the inherited implementation of this method.protected freemarker.template.ObjectWrapperGet the configured FreeMarkerObjectWrapper, or the default wrapper if none specified.protected freemarker.template.SimpleHashgetTemplateModel(Map<String, Object> model, ServerWebExchange exchange) Build a FreeMarker template model for the given model map.protected reactor.core.publisher.Mono<freemarker.template.Template> lookupTemplate(Locale locale) Retrieve the FreeMarkerTemplateto be rendered by this view, for the specified locale and using the configured encoding if set.protected freemarker.template.ConfigurationObtain the FreeMarkerConfigurationfor actual use.protected reactor.core.publisher.Mono<Void> renderInternal(Map<String, Object> renderAttributes, @nullable MediaType contentType, ServerWebExchange exchange) Subclasses must implement this method to actually render the view.reactor.core.publisher.Mono<Boolean> resourceExists(Locale locale) Check that the FreeMarker template used for this view exists and is valid.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.voidsetExposeSpringMacroHelpers(boolean exposeSpringMacroHelpers) Set whether to expose aRequestContextfor use by Spring's macro library, under the name "springMacroRequestContext".Methods inherited from class AbstractUrlBasedView
getUrl, setUrl, toStringMethods inherited from class AbstractView
createRequestContext, formatViewName, getApplicationContext, getBeanName, getDefaultCharset, getRequestContextAttribute, getRequestDataValueProcessor, getSupportedMediaTypes, obtainApplicationContext, render, resolveAsyncAttributes, setApplicationContext, setBeanName, setDefaultCharset, setRequestContextAttribute, setSupportedMediaTypesMethods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface View
isRedirectView
-
Field Details
-
SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE
Attribute name of theRequestContextinstance in the template model, available to Spring's macros — for example, for creatingBindStatusobjects.- Since:
- 5.2
- See Also:
-
-
Constructor Details
-
FreeMarkerView
public FreeMarkerView()
-
-
Method Details
-
setConfiguration
Set the FreeMarkerConfigurationto be used by this view.Typically this property is not set directly. Instead a single
FreeMarkerConfigis expected in the Spring application context which is used to obtain the FreeMarker configuration. -
getConfiguration
Get 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 noConfigurationobject set- See Also:
-
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. Note, however, thatFreeMarkerConfigurersets the default encoding in the FreeMarkerConfigurationto "UTF-8".It's recommended to specify the encoding in the FreeMarker
Configurationrather than per template if all your templates share a common encoding.Note that the specified or default encoding is not used for template rendering. Instead, an explicit encoding must be specified for the rendering process. See the note in the class-level documentation for details.
- 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
-
setExposeSpringMacroHelpers
public void setExposeSpringMacroHelpers(boolean exposeSpringMacroHelpers) Set whether to expose aRequestContextfor use by Spring's macro library, under the name "springMacroRequestContext".Default is
true.Needed for Spring's FreeMarker default macros. Note that this is not required for templates that use HTML forms unless you wish to take advantage of the Spring helper macros.
- Since:
- 5.2
- See Also:
-
afterPropertiesSet
Description copied from interface:InitializingBeanInvoked by the containingBeanFactoryafter it has set all bean properties and satisfiedBeanFactoryAware,ApplicationContextAwareetc.This method allows the bean instance to perform validation of its overall configuration and final initialization when all bean properties have been set.
- Specified by:
afterPropertiesSetin interfaceInitializingBean- Overrides:
afterPropertiesSetin classAbstractUrlBasedView- Throws:
Exception- in the event of misconfiguration (such as failure to set an essential property) or if initialization fails for any other reason
-
autodetectConfiguration
Autodetect aFreeMarkerConfigobject in theApplicationContext.- Returns:
- the
FreeMarkerConfiginstance to use for this view - Throws:
BeansException- if noFreeMarkerConfiginstance could be found- See Also:
-
checkResourceExists
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.
- Specified by:
checkResourceExistsin classAbstractUrlBasedView- Parameters:
locale- the desired Locale that we're looking for- Returns:
falseif the resource existsfalseif we know that it does not exist
-
resourceExists
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:
resourceExistsin classAbstractUrlBasedView- Parameters:
locale- the desired Locale that we're looking for- Returns:
falseif the resource existsfalseif we know that it does not exist- Since:
- 6.1
-
getModelAttributes
protected reactor.core.publisher.Mono<Map<String,Object>> getModelAttributes(@nullable Map<String, ?> model, ServerWebExchange exchange) Prepare the model to use for rendering by potentially exposing aRequestContextfor use in Spring FreeMarker macros and then delegating to the inherited implementation of this method.- Overrides:
getModelAttributesin classAbstractView- Since:
- 5.2
- See Also:
-
renderInternal
protected reactor.core.publisher.Mono<Void> renderInternal(Map<String, Object> renderAttributes, @nullable MediaType contentType, ServerWebExchange exchange) Description copied from class:AbstractViewSubclasses must implement this method to actually render the view.- Specified by:
renderInternalin classAbstractView- Parameters:
renderAttributes- combined output Map (nevernull), with dynamic values taking precedence over static attributescontentType- the content type selected to render with, which should match one of the supported media typesexchange- current exchange- Returns:
- a
Monothat represents when and if rendering succeeds
-
getTemplateModel
protected freemarker.template.SimpleHash getTemplateModel(Map<String, Object> model, ServerWebExchange exchange) Build a FreeMarker template model for the given model map.The default implementation builds a
SimpleHash.- Parameters:
model- the model to use for renderingexchange- current exchange- Returns:
- the FreeMarker template model, as a
SimpleHashor subclass thereof
-
getObjectWrapper
protected freemarker.template.ObjectWrapper getObjectWrapper()Get the configured FreeMarkerObjectWrapper, or the default wrapper if none specified.- See Also:
-
lookupTemplate
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, and the returned mono will subscribe on the bounded elastic scheduler as template lookups can be blocking operations.
- Parameters:
locale- the current locale- Returns:
- the FreeMarker template to render
- Since:
- 6.1
-