public class Configuration extends Configurable implements java.lang.Cloneable
This class is meant to be used in a singleton pattern. That is, you create an instance of this at the beginning of
the application life-cycle, set its configuration settings
there (either with the
setter methods or by loading a .properties
file), and then use that single instance everywhere in your
application. Frequently re-creating Configuration
is a typical and grave mistake from performance standpoint,
as the Configuration
holds the template cache, and often also the class introspection cache, which then will
be lost. (Note that, naturally, having multiple long-lived instances, like one per component that internally uses
FreeMarker is fine.)
The basic usage pattern is like:
// Where the application is initialized; in general you do this ONLY ONCE in the application life-cycle! Configuration cfg = new Configuration(); cfg.setSomeSetting(...); cfg.setOtherSetting(...); ... // Later, whenever the application needs a template (so you may do this a lot, and from multiple threads):Template
myTemplate = cfg.getTemplate
("myTemplate.html"); myTemplate.process
(dataModel, out);
A couple of settings that you should not leave on its default value are:
template_loader
: The default value is deprecated and in fact quite
useless. (Most user can use the convenience methods setDirectoryForTemplateLoading(File)
,
setClassForTemplateLoading(Class, String)
too.)
default_encoding
: The default value is system dependent, which makes it
fragile on servers, so it should be set explicitly, like to "UTF-8" nowadays.
incompatible_improvements
: As far the 1st and 2nd version number
remains, it's quite safe to set it as high as possible, so for new or actively developed products it's
recommended to do.
template_exception_handler
: For developing
HTML pages, the most convenient value is TemplateExceptionHandler.HTML_DEBUG_HANDLER
. For production,
TemplateExceptionHandler.RETHROW_HANDLER
is safer to use.
A Configuration
object is thread-safe only after you have stopped modify the configuration settings.
Generally, you set everything directly after you have instantiated the Configuration
object, then you don't
change the settings anymore, so then it's safe to make it accessible from multiple threads.
Configurable.UnknownSettingException
Modifier and Type | Field and Description |
---|---|
static int |
ANGLE_BRACKET_TAG_SYNTAX |
static int |
AUTO_DETECT_TAG_SYNTAX |
static java.lang.String |
AUTO_IMPORT_KEY |
static java.lang.String |
AUTO_INCLUDE_KEY |
static java.lang.String |
CACHE_STORAGE_KEY |
static java.lang.String |
DEFAULT_ENCODING_KEY |
static java.lang.String |
DEFAULT_INCOMPATIBLE_ENHANCEMENTS
Deprecated.
Use
DEFAULT_INCOMPATIBLE_IMPROVEMENTS instead. |
static Version |
DEFAULT_INCOMPATIBLE_IMPROVEMENTS
The default of
getIncompatibleImprovements() , currently new Version(2, 3, 0) . |
static java.lang.String |
INCOMPATIBLE_ENHANCEMENTS
Deprecated.
Use
INCOMPATIBLE_IMPROVEMENTS instead. |
static java.lang.String |
INCOMPATIBLE_IMPROVEMENTS |
static java.lang.String |
LOCALIZED_LOOKUP_KEY |
static int |
PARSED_DEFAULT_INCOMPATIBLE_ENHANCEMENTS
Deprecated.
Use
DEFAULT_INCOMPATIBLE_IMPROVEMENTS instead. |
static int |
SQUARE_BRACKET_TAG_SYNTAX |
static java.lang.String |
STRICT_SYNTAX_KEY |
static java.lang.String |
TAG_SYNTAX_KEY |
static java.lang.String |
TEMPLATE_UPDATE_DELAY_KEY |
static java.lang.String |
WHITESPACE_STRIPPING_KEY |
ARITHMETIC_ENGINE_KEY, AUTO_FLUSH_KEY, BOOLEAN_FORMAT_KEY, CLASSIC_COMPATIBLE_KEY, DATE_FORMAT_KEY, DATETIME_FORMAT_KEY, LOCALE_KEY, NEW_BUILTIN_CLASS_RESOLVER_KEY, NUMBER_FORMAT_KEY, OBJECT_WRAPPER_KEY, OUTPUT_ENCODING_KEY, STRICT_BEAN_MODELS, TEMPLATE_EXCEPTION_HANDLER_KEY, TIME_FORMAT_KEY, TIME_ZONE_KEY, URL_ESCAPING_CHARSET_KEY
Constructor and Description |
---|
Configuration() |
Modifier and Type | Method and Description |
---|---|
void |
addAutoImport(java.lang.String namespaceVarName,
java.lang.String templateName)
Adds an invisible
#import templateName as namespaceVarName at the beginning of all
templates. |
void |
addAutoInclude(java.lang.String templateName)
Adds an invisible
#include templateName as namespaceVarName at the beginning of all
templates. |
void |
clearEncodingMap()
Clears language-to-encoding map.
|
void |
clearSharedVariables()
Removes all shared sharedVariables, except the predefined ones (compress, html_escape, etc.).
|
void |
clearTemplateCache()
Removes all entries from the template cache, thus forcing reloading of templates
on subsequent
getTemplate calls. |
java.lang.Object |
clone() |
protected void |
doAutoImportsAndIncludes(Environment env) |
CacheStorage |
getCacheStorage()
The getter pair of
setCacheStorage(CacheStorage) . |
static Configuration |
getDefaultConfiguration()
Deprecated.
The usage of the static singleton (the "default")
Configuration instance can easily cause erroneous, unpredictable
behavior. This is because multiple independent software components may use
FreeMarker internally inside the same application, so they will interfere
because of the common Configuration instance. Each such component
should use its own private Configuration object instead, that it
typically creates with new Configuration() when the component
is initialized. |
java.lang.String |
getDefaultEncoding()
Gets the default encoding for converting bytes to characters when
reading template files in a locale for which no explicit encoding
was specified.
|
java.lang.String |
getEncoding(java.util.Locale locale)
Gets the preferred character encoding for the given locale, or the
default encoding if no encoding is set explicitly for the specified
locale.
|
java.lang.String |
getIncompatibleEnhancements()
Deprecated.
Use
getIncompatibleImprovements() instead. |
Version |
getIncompatibleImprovements() |
boolean |
getLocalizedLookup()
The getter pair of
setLocalizedLookup(boolean) . |
int |
getParsedIncompatibleEnhancements()
Deprecated.
Use
getIncompatibleImprovements() instead. |
TemplateModel |
getSharedVariable(java.lang.String name)
Gets a shared variable.
|
java.util.Set |
getSharedVariableNames()
Returns the set containing the names of all defined shared sharedVariables.
|
boolean |
getStrictSyntaxMode()
The getter pair of
setStrictSyntaxMode(boolean) . |
java.util.Set |
getSupportedBuiltInNames()
Returns the names of the supported "built-ins".
|
int |
getTagSyntax()
The getter pair of
setTagSyntax(int) . |
Template |
getTemplate(java.lang.String name)
Retrieves the template with the given name from the template cache, loading it into the cache first if it's
missing/staled.
|
Template |
getTemplate(java.lang.String name,
java.util.Locale locale)
Shorthand for
getTemplate(name, locale, getEncoding(locale), true) . |
Template |
getTemplate(java.lang.String name,
java.util.Locale locale,
java.lang.String encoding)
Shorthand for
getTemplate(name, locale, encoding, true) . |
Template |
getTemplate(java.lang.String name,
java.util.Locale locale,
java.lang.String encoding,
boolean parseAsFTL)
Retrieves the template with the given name (and according the specified further parameters) from the template
cache, loading it into the cache first if it's missing/staled.
|
Template |
getTemplate(java.lang.String name,
java.lang.String encoding)
Shorthand for
getTemplate(name, getLocale(), encoding, true) . |
TemplateLoader |
getTemplateLoader()
The getter pair of
setTemplateLoader(TemplateLoader) . |
static Version |
getVersion()
Returns the FreeMarker version information, most importantly the major.minor.micro version numbers.
|
static java.lang.String |
getVersionNumber()
Deprecated.
Use
getVersion() instead. |
boolean |
getWhitespaceStripping()
Gets whether the FTL parser will try to remove
superfluous white-space around certain FTL tags.
|
void |
loadBuiltInEncodingMap()
Loads a preset language-to-encoding map.
|
void |
removeAutoImport(java.lang.String namespaceVarName)
Removes an auto-import; see
addAutoImport(String, String) . |
void |
removeAutoInclude(java.lang.String templateName)
Removes a template from the auto-include list; see
addAutoInclude(String) . |
void |
removeTemplateFromCache(java.lang.String name)
Equivalent to removeTemplateFromCache(name, thisCfg.getLocale(), thisCfg.getEncoding(thisCfg.getLocale()), true).
|
void |
removeTemplateFromCache(java.lang.String name,
java.util.Locale locale)
Equivalent to removeTemplateFromCache(name, locale, thisCfg.getEncoding(locale), true).
|
void |
removeTemplateFromCache(java.lang.String name,
java.util.Locale locale,
java.lang.String encoding)
Equivalent to removeTemplateFromCache(name, locale, encoding, true).
|
void |
removeTemplateFromCache(java.lang.String name,
java.util.Locale locale,
java.lang.String encoding,
boolean parse)
Removes a template from the template cache, hence forcing the re-loading
of it when it's next time requested.
|
void |
removeTemplateFromCache(java.lang.String name,
java.lang.String encoding)
Equivalent to removeTemplateFromCache(name, thisCfg.getLocale(), encoding, true).
|
void |
setAllSharedVariables(TemplateHashModelEx hash)
Adds all object in the hash as shared variable to the configuration.
|
void |
setAutoImports(java.util.Map map)
Removes all auto-imports, then calls
addAutoImport(String, String) for each Map -entry (the entry
key is the namespaceVarName ). |
void |
setAutoIncludes(java.util.List templateNames)
Removes all auto-includes, then calls
addAutoInclude(String) for each List items. |
void |
setCacheStorage(CacheStorage storage)
Sets the
CacheStorage used for caching Template -s. |
void |
setClassForTemplateLoading(java.lang.Class clazz,
java.lang.String pathPrefix)
Sets a class relative to which we do the Class.getResource() call to load templates.
|
static void |
setDefaultConfiguration(Configuration config)
Deprecated.
Using the "default"
Configuration instance can
easily lead to erroneous, unpredictable behaviour.
See more here... . |
void |
setDefaultEncoding(java.lang.String encoding)
Sets the default encoding for converting bytes to characters when
reading template files in a locale for which no explicit encoding
was specified.
|
void |
setDirectoryForTemplateLoading(java.io.File dir)
Sets the file system directory from which to load templates.
|
void |
setEncoding(java.util.Locale locale,
java.lang.String encoding)
Sets the character set encoding to use for templates of
a given locale.
|
void |
setIncompatibleEnhancements(java.lang.String version)
Deprecated.
Use
setIncompatibleImprovements(Version) instead. |
void |
setIncompatibleImprovements(Version version)
Sets which of the non-backward-compatible bugfixes/improvements should be enabled.
|
void |
setLocalizedLookup(boolean localizedLookup)
Enables/disables localized template lookup.
|
void |
setServletContextForTemplateLoading(java.lang.Object servletContext,
java.lang.String path)
Sets the servlet context from which to load templates.
|
void |
setSetting(java.lang.String key,
java.lang.String value)
Sets a FreeMarker setting by a name and string value.
|
void |
setSharedVariable(java.lang.String name,
java.lang.Object obj)
Adds shared variable to the configuration.
|
void |
setSharedVariable(java.lang.String name,
TemplateModel tm)
Adds a shared variable to the configuration.
|
void |
setStrictSyntaxMode(boolean b)
Deprecated.
Only
true (the default) value will be supported sometimes in the future. |
void |
setTagSyntax(int tagSyntax)
Determines the syntax of the template files (angle bracket VS square bracket)
that has no
#ftl in it. |
void |
setTemplateLoader(TemplateLoader loader)
Sets a
TemplateLoader that is used to look up and load templates. |
void |
setTemplateUpdateDelay(int seconds)
Sets the time in seconds that must elapse before checking whether there is a newer version of a template file
than the cached one.
|
void |
setWhitespaceStripping(boolean b)
Sets whether the FTL parser will try to remove
superfluous white-space around certain FTL tags.
|
getArithmeticEngine, getAutoFlush, getBooleanFormat, getClassicCompatibleAsInt, getCustomAttribute, getCustomAttributeNames, getDateFormat, getDateTimeFormat, getEnvironment, getLocale, getNewBuiltinClassResolver, getNumberFormat, getObjectWrapper, getOutputEncoding, getParent, getSetting, getSettings, getTemplateExceptionHandler, getTimeFormat, getTimeZone, getURLEscapingCharset, invalidSettingValueException, isClassicCompatible, parseAsImportList, parseAsList, parseAsSegmentedList, removeCustomAttribute, setArithmeticEngine, setAutoFlush, setBooleanFormat, setClassicCompatible, setClassicCompatibleAsInt, setCustomAttribute, setDateFormat, setDateTimeFormat, setLocale, setNewBuiltinClassResolver, setNumberFormat, setObjectWrapper, setOutputEncoding, setSettings, setSettings, setStrictBeanModels, setTemplateExceptionHandler, setTimeFormat, setTimeZone, setURLEscapingCharset, unknownSettingException
public static final java.lang.String DEFAULT_ENCODING_KEY
public static final java.lang.String LOCALIZED_LOOKUP_KEY
public static final java.lang.String STRICT_SYNTAX_KEY
public static final java.lang.String WHITESPACE_STRIPPING_KEY
public static final java.lang.String CACHE_STORAGE_KEY
public static final java.lang.String TEMPLATE_UPDATE_DELAY_KEY
public static final java.lang.String AUTO_IMPORT_KEY
public static final java.lang.String AUTO_INCLUDE_KEY
public static final java.lang.String TAG_SYNTAX_KEY
public static final java.lang.String INCOMPATIBLE_IMPROVEMENTS
public static final java.lang.String INCOMPATIBLE_ENHANCEMENTS
INCOMPATIBLE_IMPROVEMENTS
instead.public static final int AUTO_DETECT_TAG_SYNTAX
public static final int ANGLE_BRACKET_TAG_SYNTAX
public static final int SQUARE_BRACKET_TAG_SYNTAX
public static final Version DEFAULT_INCOMPATIBLE_IMPROVEMENTS
getIncompatibleImprovements()
, currently new Version(2, 3, 0)
.public static final java.lang.String DEFAULT_INCOMPATIBLE_ENHANCEMENTS
DEFAULT_INCOMPATIBLE_IMPROVEMENTS
instead.public static final int PARSED_DEFAULT_INCOMPATIBLE_ENHANCEMENTS
DEFAULT_INCOMPATIBLE_IMPROVEMENTS
instead.public java.lang.Object clone()
clone
in class Configurable
public void loadBuiltInEncodingMap()
ar | ISO-8859-6 |
be | ISO-8859-5 |
bg | ISO-8859-5 |
ca | ISO-8859-1 |
cs | ISO-8859-2 |
da | ISO-8859-1 |
de | ISO-8859-1 |
el | ISO-8859-7 |
en | ISO-8859-1 |
es | ISO-8859-1 |
et | ISO-8859-1 |
fi | ISO-8859-1 |
fr | ISO-8859-1 |
hr | ISO-8859-2 |
hu | ISO-8859-2 |
is | ISO-8859-1 |
it | ISO-8859-1 |
iw | ISO-8859-8 |
ja | Shift_JIS |
ko | EUC-KR |
lt | ISO-8859-2 |
lv | ISO-8859-2 |
mk | ISO-8859-5 |
nl | ISO-8859-1 |
no | ISO-8859-1 |
pl | ISO-8859-2 |
pt | ISO-8859-1 |
ro | ISO-8859-2 |
ru | ISO-8859-5 |
sh | ISO-8859-5 |
sk | ISO-8859-2 |
sl | ISO-8859-2 |
sq | ISO-8859-2 |
sr | ISO-8859-5 |
sv | ISO-8859-1 |
tr | ISO-8859-9 |
uk | ISO-8859-5 |
zh | GB2312 |
zh_TW | Big5 |
public void clearEncodingMap()
public static Configuration getDefaultConfiguration()
Configuration
instance can easily cause erroneous, unpredictable
behavior. This is because multiple independent software components may use
FreeMarker internally inside the same application, so they will interfere
because of the common Configuration
instance. Each such component
should use its own private Configuration
object instead, that it
typically creates with new Configuration()
when the component
is initialized.public static void setDefaultConfiguration(Configuration config)
Configuration
instance can
easily lead to erroneous, unpredictable behaviour.
See more here...
.getDefaultConfiguration()
.public void setTemplateLoader(TemplateLoader loader)
TemplateLoader
that is used to look up and load templates.
By providing your own TemplateLoader
implementation, you can load templates from whatever kind of
storages, like from relational databases, NoSQL-storages, etc.
Convenience methods exists to install commonly used loaders, instead of using this method:
setClassForTemplateLoading(Class, String)
,
setDirectoryForTemplateLoading(File)
, and
setServletContextForTemplateLoading(Object, String)
.
You can chain several TemplateLoader
-s together with MultiTemplateLoader
.
Default value: You should always set the template loader instead of relying on the default value. The a default value is there only for backward compatibility, and it will be probably removed in the future. It's a multi-loader that first tries to load a template from the file in the current directory, then from a resource on the classpath.
Note that setting the template loader will re-create the template cache, so all its content will be lost.
public TemplateLoader getTemplateLoader()
setTemplateLoader(TemplateLoader)
.public void setCacheStorage(CacheStorage storage)
CacheStorage
used for caching Template
-s. The
default is a SoftCacheStorage
. If the total size of the Template
objects is significant but most templates are used rarely, using a
MruCacheStorage
instead might be advisable. If you don't want caching at
all, use NullCacheStorage
(you can't use null
).
Note that setting the cache storage will re-create the template cache, so all its content will be lost.
public CacheStorage getCacheStorage()
setCacheStorage(CacheStorage)
.public void setDirectoryForTemplateLoading(java.io.File dir) throws java.io.IOException
setTemplateLoader(new FileTemplateLoader(dir))
,
so see FileTemplateLoader.FileTemplateLoader(File)
for more details.
Note that FreeMarker can load templates from non-file-system sources too.
See setTemplateLoader(TemplateLoader)
from more details.java.io.IOException
public void setServletContextForTemplateLoading(java.lang.Object servletContext, java.lang.String path)
setTemplateLoader(new WebappTemplateLoader(sctxt, path))
or setTemplateLoader(new WebappTemplateLoader(sctxt))
if path
was
null
, so see WebappTemplateLoader
for more details.servletContext
- the ServletContext
object. (The declared type is Object
to prevent class loading error when using FreeMarker in an environment where
there's no servlet classes available.)path
- the path relative to the ServletContext.setTemplateLoader(TemplateLoader)
public void setClassForTemplateLoading(java.lang.Class clazz, java.lang.String pathPrefix)
setTemplateLoader(new ClassTemplateLoader(clazz, pathPrefix))
,
so see ClassTemplateLoader.ClassTemplateLoader(Class, String)
for more details.setTemplateLoader(TemplateLoader)
public void setTemplateUpdateDelay(int seconds)
public void setStrictSyntaxMode(boolean b)
true
(the default) value will be supported sometimes in the future.if
, else
, etc must be written as #if
, #else
, etc.
Defaults to true
.
When this is true
,
any tag not starting with <# or </# or <@ or </@ is considered as plain text
and will go to the output as is. Tag starting with <# or </# must
be valid FTL tag, or else the template is invalid (i.e. <#noSuchDirective>
is an error).
public boolean getStrictSyntaxMode()
setStrictSyntaxMode(boolean)
.public void setIncompatibleImprovements(Version version)
The default value is 2.3.0 for maximum backward-compatibility when upgrading freemkarer.jar
under an
existing application. But if you develop a new application with, say, 2.3.20, it's probably a good idea to set
this from 2.3.0 to 2.3.20. As far as the 1st and 2nd version number remains, these changes are always very
low-risk changes, so usually they don't break anything in older applications either.
This setting doesn't affect some important non-backward compatible security fixes; they are always enabled, regardless of what you set here.
Incrementing this setting is a good way of preparing for the next minor (2nd) or major (1st) version number increases. When that happens, it's possible that some old behavior become unsupported, that is, even if you set this setting to a low value, it might wont bring back the old behavior anymore.
Currently the effects of this setting are:
2.3.19 (or higher): Bug fix: Wrong #
tags were printed as static text instead of
causing parsing error when there was no correct #
or @
tag earlier in the
same template.
2.3.20 (or higher): ?html
will escape apostrophe-quotes just like ?xhtml
does. Utilizing
this is highly recommended, because otherwise if interpolations are used inside attribute values that use
apostrophe-quotation (<foo bar='${val}'>) instead of plain quotation mark
(<foo bar="${val}">), they might produce HTML/XML that's not well-formed. Note that
?html
didn't do this because long ago there was no cross-browser way of doing this, but it's not a
concern anymore.
public Version getIncompatibleImprovements()
setIncompatibleImprovements(Version)
public void setIncompatibleEnhancements(java.lang.String version)
setIncompatibleImprovements(Version)
instead.public java.lang.String getIncompatibleEnhancements()
getIncompatibleImprovements()
instead.public int getParsedIncompatibleEnhancements()
getIncompatibleImprovements()
instead.public void setWhitespaceStripping(boolean b)
public boolean getWhitespaceStripping()
setWhitespaceStripping(boolean)
public void setTagSyntax(int tagSyntax)
#ftl
in it. The tagSyntax
parameter must be one of:
AUTO_DETECT_TAG_SYNTAX
:
use the syntax of the first FreeMarker tag (can be anything, like #list,
#include, user defined, etc.)
ANGLE_BRACKET_TAG_SYNTAX
:
use the angle bracket syntax (the normal syntax)
SQUARE_BRACKET_TAG_SYNTAX
:
use the square bracket syntax
In FreeMarker 2.3.x ANGLE_BRACKET_TAG_SYNTAX
is the
default for better backward compatibility. Starting from 2.4.x AUTO_DETECT_TAG_SYNTAX
is the default, so it's recommended to use
that even for 2.3.x.
This setting is ignored for the templates that have ftl
directive in
it. For those templates the syntax used for the ftl
directive determines
the syntax.
public int getTagSyntax()
setTagSyntax(int)
.public Template getTemplate(java.lang.String name) throws java.io.IOException
This is a shorthand for getTemplate(name, getLocale(), getEncoding(getLocale()), true)
; see more details there.
See Configuration
for an example of basic usage.
java.io.IOException
public Template getTemplate(java.lang.String name, java.util.Locale locale) throws java.io.IOException
getTemplate(name, locale, getEncoding(locale), true)
.java.io.IOException
public Template getTemplate(java.lang.String name, java.lang.String encoding) throws java.io.IOException
getTemplate(name, getLocale(), encoding, true)
.java.io.IOException
public Template getTemplate(java.lang.String name, java.util.Locale locale, java.lang.String encoding) throws java.io.IOException
getTemplate(name, locale, encoding, true)
.java.io.IOException
public Template getTemplate(java.lang.String name, java.util.Locale locale, java.lang.String encoding, boolean parseAsFTL) throws java.io.IOException
See Configuration
for an example of basic usage.
name
- The name of the template. Can't be null
. The exact syntax of the name
is interpreted by the underlying TemplateLoader
, but the
cache makes some assumptions. First, the name is expected to be
a hierarchical path, with path components separated by a slash
character (not with backslash!). The path (the name) given here must not begin with slash;
it's always interpreted relative to the "template root directory".
Then, the ..
and .
path meta-elements will be resolved.
For example, if the name is a/../b/./c.ftl
, then it will be
simplified to b/c.ftl
. The rules regarding this are same as with conventional
UN*X paths. The path must not reach outside the template root directory, that is,
it can't be something like "../templates/my.ftl"
(not even if this path
happens to be equivalent with "/my.ftl"
).
Further, the path is allowed to contain at most
one path element whose name is *
(asterisk). This path meta-element triggers the
acquisition mechanism. If the template is not found in
the location described by the concatenation of the path left to the
asterisk (called base path) and the part to the right of the asterisk
(called resource path), the cache will attempt to remove the rightmost
path component from the base path ("go up one directory") and concatenate
that with the resource path. The process is repeated until either a
template is found, or the base path is completely exhausted.locale
- The requested locale of the template. Can't be null
.
Assuming you have specified en_US
as the locale and
myTemplate.ftl
as the name of the template, the cache will
first try to retrieve myTemplate_en_US.html
, then
myTemplate.en.ftl
, and finally myTemplate.ftl
.encoding
- The charset used to interpret the template source code bytes. Can't be null
.parseAsFTL
- If true
, the loaded template is parsed and interpreted normally,
as a regular FreeMarker template. If false
, the loaded template is
treated as a static text, so ${...}
, <#...>
etc. will not have special meaning
in it.null
.java.io.FileNotFoundException
- if the template could not be found.java.io.IOException
- if there was a problem loading the template.ParseException
- (extends IOException
) if the template is syntactically bad.public void setDefaultEncoding(java.lang.String encoding)
Defaults to the default system encoding, which can change from one server to another, so you should always set this setting.
encoding
- The name of the charset, such as "UTF-8"
or "ISO-8859-1"
public java.lang.String getDefaultEncoding()
public java.lang.String getEncoding(java.util.Locale locale)
setEncoding(Locale, String)
or loadBuiltInEncodingMap()
.public void setEncoding(java.util.Locale locale, java.lang.String encoding)
setDefaultEncoding(java.lang.String)
.clearEncodingMap()
,
loadBuiltInEncodingMap()
public void setSharedVariable(java.lang.String name, TemplateModel tm)
Never use TemplateModel implementation that is not thread-safe for shared sharedVariables, if the configuration is used by multiple threads! It is the typical situation for Servlet based Web sites.
name
- the name used to access the data object from your template.
If a shared variable with this name already exists, it will replace
that.setSharedVariable(String,Object)
,
setAllSharedVariables(freemarker.template.TemplateHashModelEx)
public java.util.Set getSharedVariableNames()
public void setSharedVariable(java.lang.String name, java.lang.Object obj) throws TemplateModelException
Configurable.getObjectWrapper()
to wrap the
obj
.public void setAllSharedVariables(TemplateHashModelEx hash) throws TemplateModelException
Never use TemplateModel implementation that is not thread-safe for shared sharedVariables, if the configuration is used by multiple threads! It is the typical situation for Servlet based Web sites.
hash
- a hash model whose objects will be copied to the
configuration with same names as they are given in the hash.
If a shared variable with these names already exist, it will be replaced
with those from the map.TemplateModelException
setSharedVariable(String,Object)
,
setSharedVariable(String,TemplateModel)
public TemplateModel getSharedVariable(java.lang.String name)
public void clearSharedVariables()
public void clearTemplateCache()
getTemplate
calls.
This method is thread-safe and can be called while the engine works.public void removeTemplateFromCache(java.lang.String name) throws java.io.IOException
java.io.IOException
public void removeTemplateFromCache(java.lang.String name, java.util.Locale locale) throws java.io.IOException
java.io.IOException
public void removeTemplateFromCache(java.lang.String name, java.lang.String encoding) throws java.io.IOException
java.io.IOException
public void removeTemplateFromCache(java.lang.String name, java.util.Locale locale, java.lang.String encoding) throws java.io.IOException
java.io.IOException
public void removeTemplateFromCache(java.lang.String name, java.util.Locale locale, java.lang.String encoding, boolean parse) throws java.io.IOException
setTemplateUpdateDelay(int)
alone does.
For the meaning of the parameters, see
getTemplate(String, Locale, String, boolean)
.java.io.IOException
public boolean getLocalizedLookup()
setLocalizedLookup(boolean)
.
This method is thread-safe and can be called while the engine works.
public void setLocalizedLookup(boolean localizedLookup)
Localized lookup works like this: Let's say your locale setting is "en_AU", and you call
cfg.getTemplate("foo.ftl")
. Then FreeMarker will look for the template
under names, stopping at the first that exists: "foo_en_AU.ftl"
, "foo_en.ftl"
, "foo.ftl"
.
This method is thread-safe and can be called while the engine works.
public void setSetting(java.lang.String key, java.lang.String value) throws TemplateException
Configurable
Configurable.setObjectWrapper(ObjectWrapper)
. This meant to be used if you get the settings from somewhere
as text. Regardless, below you will find an overview of the settings available no matter how you set them.
The list of settings commonly supported in all Configurable
subclasses:
"locale"
:
See Configurable.setLocale(Locale)
.
String value: local codes with the usual format in Java, such as "en_US"
.
"classic_compatible"
:
See Configurable.setClassicCompatible(boolean)
and Configurable.setClassicCompatibleAsInt(int)
.
String value: "true"
, "false"
, also since 2.3.20 0
or 1
or 2
.
(Also accepts "yes"
, "no"
, "t"
, "f"
, "y"
, "n"
.)
Case insensitive.
"template_exception_handler"
:
See Configurable.setTemplateExceptionHandler(TemplateExceptionHandler)
.
String value: If the value contains dot, then it's
interpreted as a class name, and the object will be created with
its parameterless constructor. If the value does not contain dot,
then it must be one of these predefined values (case insensitive):
"rethrow"
(means TemplateExceptionHandler.RETHROW_HANDLER
),
"debug"
(means TemplateExceptionHandler.DEBUG_HANDLER
),
"html_debug"
(means TemplateExceptionHandler.HTML_DEBUG_HANDLER
),
"ignore"
(means TemplateExceptionHandler.IGNORE_HANDLER
).
"arithmetic_engine"
:
See Configurable.setArithmeticEngine(ArithmeticEngine)
.
String value: If the value contains dot, then it's
interpreted as class name, and the object will be created with
its parameterless constructor. If the value does not contain dot,
then it must be one of these special values (case insensitive):
"bigdecimal"
, "conservative"
.
"object_wrapper"
:
See Configurable.setObjectWrapper(ObjectWrapper)
.
String value: If the value contains dot, then it's
interpreted as class name, and the object will be created with
its parameterless constructor. If the value does not contain dot,
then it must be one of these special values (case insensitive):
"default"
(means ObjectWrapper.DEFAULT_WRAPPER
),
"simple"
(means ObjectWrapper.SIMPLE_WRAPPER
),
"beans"
(means ObjectWrapper.DEFAULT_WRAPPER
),
"jython"
(means ObjectWrapper.DEFAULT_WRAPPER
)
"number_format"
: See Configurable.setNumberFormat(String)
.
"boolean_format"
: See Configurable.setBooleanFormat(String)
.
"date_format", "time_format", "datetime_format"
:
See Configurable.setDateFormat(String)
, Configurable.setTimeFormat(String)
, Configurable.setDateTimeFormat(String)
.
"time_zone"
:
See Configurable.setTimeZone(TimeZone)
.
String value: With the format as TimeZone.getTimeZone(java.lang.String)
defines it.
For example "GMT-8:00"
or "America/Los_Angeles"
"output_encoding"
:
See Configurable.setOutputEncoding(String)
.
"url_escaping_charset"
:
See Configurable.setURLEscapingCharset(String)
.
"auto_flush"
:
See Configurable.setAutoFlush(boolean)
.
Since 2.3.17.
String value: "true"
, "false"
, "y"
, etc.
"new_builtin_class_resolver"
:
See Configurable.setNewBuiltinClassResolver(TemplateClassResolver)
.
Since 2.3.17.
String value: The value must be one of these (ignore the quotation marks):
"unrestricted"
:
Use TemplateClassResolver.UNRESTRICTED_RESOLVER
"safer"
:
Use TemplateClassResolver.SAFER_RESOLVER
"allows_nothing"
:
Use TemplateClassResolver.ALLOWS_NOTHING_RESOLVER
Something that contains colon will use
OptInTemplateClassResolver
and is expected to
store comma separated values (possibly quoted) segmented
with "allowed_classes:"
and/or
"trusted_templates:"
. Examples of valid values:
Setting value | Meaning |
---|---|
allowed_classes: com.example.C1, com.example.C2,
trusted_templates: lib/*, safe.ftl
|
Only allow instantiating the com.example.C1 and
com.example.C2 classes. But, allow templates
within the lib/ directory (like
lib/foo/bar.ftl ) and template safe.ftl
(that does not match foo/safe.ftl , only
exactly safe.ftl ) to instantiate anything
that TemplateClassResolver.SAFER_RESOLVER allows.
|
allowed_classes: com.example.C1, com.example.C2
| Only allow instantiating the com.example.C1 and
com.example.C2 classes. There are no
trusted templates.
|
trusted_templates: lib/*, safe.ftl
|
Do not allow instantiating any classes, except in
templates inside lib/ or in template
safe.ftl .
|
For more details see OptInTemplateClassResolver
.
Otherwise if the value contains dot, it's interpreted as a full-qualified class name, and the object will be created with its parameterless constructor.
Configuration
(a subclass of Configurable
) also understands these:
"auto_import"
:
See setAutoImports(Map)
String value is something like:
/lib/form.ftl as f, /lib/widget as w, "/lib/odd name.ftl" as odd
"auto_include"
: Sets the list of auto-includes.
See setAutoIncludes(List)
String value is something like:
/include/common.ftl, "/include/evil name.ftl"
"default_encoding"
:
See setDefaultEncoding(String)
.
As the default value is the system default, which can change
from one server to another, you should always set this!
"localized_lookup"
:
See setLocalizedLookup(boolean)
.
String value: "true"
, "false"
(also the equivalents: "yes"
, "no"
,
"t"
, "f"
, "y"
, "n"
).
Case insensitive.
"strict_syntax"
:
See setStrictSyntaxMode(boolean)
. Deprecated.
String value: "true"
, "false"
, yes
, etc.
"whitespace_stripping"
:
See setWhitespaceStripping(boolean)
.
String value: "true"
, "false"
, yes
, etc.
"cache_storage"
:
See setCacheStorage(freemarker.cache.CacheStorage)
.
String value: If the value contains dot, then it's
interpreted as class name, and the object will be created with
its parameterless constructor. If the value does not contain dot,
then a MruCacheStorage
will be used with the
maximum strong and soft sizes specified with the setting value. Examples
of valid setting values:
Setting value | max. strong size | max. soft size |
---|---|---|
"strong:50, soft:500" | 50 | 500 |
"strong:100, soft" | 100 | Integer.MAX_VALUE
|
"strong:100" | 100 | 0 |
"soft:100" | 0 | 100 |
"strong" | Integer.MAX_VALUE | 0 |
"soft" | 0 | Integer.MAX_VALUE
|
The value is not case sensitive. The order of soft and strong entries is not significant.
"template_update_delay"
:
See setTemplateUpdateDelay(int)
.
String value: Valid positive integer, the update delay measured in seconds.
"tag_syntax"
:
See setTagSyntax(int)
.
String value: Must be one of
"auto_detect"
, "angle_bracket"
, and "square_bracket"
.
"incompatible_improvements"
:
See setIncompatibleImprovements(Version)
.
String value: version number like 2.3.20
.
"incompatible_enhancements"
:
See: setIncompatibleEnhancements(String)
.
This setting name is deprecated, use "incompatible_improvements"
instead.
setSetting
in class Configurable
key
- the name of the setting.value
- the string that describes the new value of the setting.Configurable.UnknownSettingException
- if the name is wrong.TemplateException
- if the new value of the setting can't be set for any other reasons.public void addAutoImport(java.lang.String namespaceVarName, java.lang.String templateName)
#import templateName as namespaceVarName
at the beginning of all
templates. The order of the imports will be the same as the order in which they were added with this method.public void removeAutoImport(java.lang.String namespaceVarName)
addAutoImport(String, String)
. Does nothing if the auto-import doesn't
exist.public void setAutoImports(java.util.Map map)
addAutoImport(String, String)
for each Map
-entry (the entry
key is the namespaceVarName
). The order of the auto-imports will be the same as Map.keySet()
returns the keys, thus, it's not the best idea to use a HashMap
(although the order of imports doesn't
mater for properly designed libraries).protected void doAutoImportsAndIncludes(Environment env) throws TemplateException, java.io.IOException
doAutoImportsAndIncludes
in class Configurable
TemplateException
java.io.IOException
public void addAutoInclude(java.lang.String templateName)
#include templateName as namespaceVarName
at the beginning of all
templates. The order of the inclusions will be the same as the order in which they were added with this method.public void setAutoIncludes(java.util.List templateNames)
addAutoInclude(String)
for each List
items.public void removeAutoInclude(java.lang.String templateName)
addAutoInclude(String)
. Does nothing if the template
is not there.public static java.lang.String getVersionNumber()
getVersion()
instead.public static Version getVersion()
public java.util.Set getSupportedBuiltInNames()
expr?builtin_name
-like things). As of this
writing, this information doesn't depend on the configuration options, so it could be a static method, but
to be future-proof, it's an instance method.Set
of String
-s.