FreeMarker configures of Configuration

  • 2020-05-09 18:37:35
  • OfStack

p > basis

Configuration is an object that holds common configuration information at the application level (application level) and global Shared variables that can be used by templates (Template). It is also responsible for the creation and caching of template (Template) instances. Configuration is actually an instance of the freemarker.template.Configuration   object, created using its constructor. Applications typically use a single Shared Configuration object.

The Configuration object can be used by the Template object method. Each template instance is associated with an Configuration instance. It is associated with the Template constructor, which is usually the method you use to obtain the Configuration.getTemplate   template object.

 

Shared variables

Shared variables are those defined for use by all templates (Template). You can add Shared variables through the setSharedVariable   method of the configuration object.


Configuration cfg = new Configuration(); ... cfg.setSharedVariable("wrap", new WrapDirective()); cfg.setSharedVariable("company", "Foo Inc."); // Using ObjectWrapper.DEFAULT_WRAPPER

All template instances associated with the configuration object can get the string by getting to_upper   converter, company  , so you don't need to add these variables to root a second time. If you add a variable with the same name to root, your new variable will override the previously Shared variable.

Warning!

If the configuration objects are called by multiple threads, do not use the TemplateModel implementation classes as Shared variables because they are non-thread-safe, as is the case with servlet-based web sites.

When the Configuration object is initialized, it already contains 1 Shared converter variables:

Name the class

name class capture_output freemarker.template.utility.CaptureOutput compress freemarker.template.utility.StandardCompress html_escape freemarker.template.utility.HtmlEscape normalize_newlines freemarker.template.utility.NormalizeNewlines xml_escape freemarker.template.utility.XmlEscape

 

 

Configuration parameters

Configuration parameters are named parameters that can affect the behavior of the FreeMarker run. For example, locale number_format.

The configuration parameter is stored in the Configuration instance, which can be modified by the template instance (Template). For example, if you set locale equal to "en_US" in Configuration, then all template objects will be used, "en_US" unless you change the default configuration using the setLocale method in a single template instance. Therefore, the parameters set by configuration can be regarded as the default parameters, which can be overwritten by the parameters set by Template1 level, and the parameter information set by both of them can be overwritten by the parameters set in the environment (that is, the template file instruction is set) as follows:


${1.2}<#setting locale="en_US">${1.2}


This way of calling can be thought of as three layers (configuration object layer, template layer, and runtime environment layer). The following table shows the Settings of parameters for each layer:

Setting A Setting B Setting C Setting D Setting E Setting F Layer 3:Environment 1 - - 1 - - Layer 2:Template 2 2 - - 2 - Layer 1:Configuration 3 3 3 3 - -

Then the final results of configuration parameters are: A = 1, B = 2, C = 3, D = 1, E = 2, and F parameter is likely to be null.

For a list of settable parameters, you can refer to the following two sections of the FreeMarker API document:
Configuration of all layers


freemarker.core.Configurable.setSetting(String, String)


Configuration of the Coniguration layer


freemarker.template.Configuration.setSetting(String,String)


To load a template


Template loader

The template loader is the object that loads the raw data based on the abstract path (" index.ftl "or "products/ catalog.ftl"), and exactly which resource to load (file data in the directory or data in the database) depends on the specific loader implementation. When you call cfg.getTemplate  , FreeMarker will ask you about the template loader you configured for the Configuration object, which is responsible for loading the file.

Built-in template loader
You can set the template load in three different ways using the following three methods


void setDirectoryForTemplateLoading(File dir);


or


void setClassForTemplateLoading(Class cl, String prefix);


or


void setServletContextForTemplateLoading(Object servletContext, String path);


The first method above specifies a directory in the file system. FreeMarker will record templates in this directory. Needless to say, this directory must exist, otherwise an exception will be thrown.

The second method takes 1 Class as an input parameter. When you want to load the template using ClassLoader, you can use this method. This method will be called to find the template file, and this mode of template loading is more stable than the first one, especially in production systems. You can easily package resource files, ICONS, etc. into.jar files.

The third takes as arguments the context in which web is applied and the base path (as opposed to the parent path of WEN-INF). The template loader in this way will load the template from web using the context class.

Load templates from multiple locations

If you want to load templates from multiple locations, you can create a single template loader for each location, wrap them into a template loader called MultiTemplateLoader, and finally set it to the Configuration object via the setTemplateLoader(TemplateLoader loader) method. Here is an example of loading templates from two different locations:


import freemarker.cache.*; // template loaders live in this package ... FileTemplateLoader ftl1 = new FileTemplateLoader(new File("/tmp/templates")); FileTemplateLoader ftl2 = new FileTemplateLoader(new File("/usr/data/templates")); ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(), ""); TemplateLoader[] loaders = new TemplateLoader[] { ftl1, ftl2, ctl }; MultiTemplateLoader mtl = new MultiTemplateLoader(loaders); cfg.setTemplateLoader(mtl); 


FreeMarker will first search the template file in the path /tmp/templates. If it is not found, then go back to the path /usr/data/templates. If it is not found, then try to load it with class-loader.

Get template files from other resources

If none of these built-in template loaders meets your requirements, you can customize a template loader yourself by simply implementing the freemarker.cache.TemplateLoader   interface and passing it to the Configuration object via the setTemplateLoader(TemplateLoader loader) method.

Cache the template

FreeMarker cache template means that when you get a template through the getTemplate method, FreeMarker will not only return an Template object, but it will also cache the object, and when you next request the template in the same path, it will return the template object in the cache. If you change the template file, the next time you get the template, FreeMarker will automatically reload and reparse the template. Nonetheless, if it is a time-consuming operation to directly determine whether a file has been modified, then FreeMarker provides a configuration parameter "update delay" at the Configuration object level. This parameter means how long it takes FreeMarker to judge the version of a template. The default setting is 5 seconds, which means every 5 seconds will determine whether the template has been modified or not. If you want to judge in real time, set this parameter to 0. Another point to note is that not all loaders support this approach. For example, a template loader based on class-loader will not notice that you have modified the template file.

This is done for removing templates FreeMarker from the cache. You can use the Configuration object method clearTemplateCache   to manually clear the template objects in the cache. In fact, the cache part can be added to FreeMarker as a component (that is, it can use the 3rd party caching scheme) by setting the parameter cache_storage  . The freemarker.cache.MruCacheStorage   implementation that comes with FreeMarker is sufficient for most developers. This cache USES two levels of the Most Recently Used (most recently used) policy. At the first level, all cache entries use strong references (strongly referenced: entries are not known to JVM, as opposed to weak references softly reference) until the maximum time is reached, and the least recently used entries are migrated to level 2 cache. At this level, entries use weak references until they expire. If the size of the reference and strong reference regions can be set in the constructor, for example, if you want to set the strong reference region to 20 and the weak reference region to 250, you can use the following code:


cfg.setCacheStorage(new freemarker.cache.MruCacheStorage(20, 250))


Since MruCacheStorage is the default cache implementation, you can also set it like this:


cfg.setSetting(Configuration.CACHE_STORAGE_KEY,"strong:20, soft:250");


When you create a new Configuration, it is implemented by default using the MruCacheStorage cache and the default value maxStrongSize is equal to 0, maxSoftSize is equal to Integer.MAX_VALUE (the theoretical maximum). However, for high-load systems, we recommend that maxStrongSize   be set to a non-zero value, which will result in frequent reloading and reparsing of the template.

 

Exception handling

Possible exceptions

The exception 1 generated by FreeMarker generally falls into the following categories:

Exceptions during the initialization phase of FreeMarker: usually, you only need to initialize FreeMarker once in your application, but when the class generates an exception during this time period, it is called an initialization exception.

Load parse template exceptions: when you get a template from the Configuration.getTemplate () method (if the template was not previously cached), there are two types of exceptions:

IOException: because the template was not found, or other IO exception occurred when reading the template, such as you do not have the right to read the file, etc.; freemarker. core. ParseException due to incorrect use of template file syntax;

Exception during execution: when you call Template.process (...) Methods throw two types of exceptions:

IOException error while writing data to output; freemarker.template.TemplatException other runtime exceptions, such as one of the most common errors is that the template refers to a variable that does not exist;


Related articles: