Freemarker configuration (Configuration) _java

Source: Internet
Author: User
Tags exception handling locale

P> Foundation

Configuration is an object that holds public configuration information for application levels (application level) and global shared variables that templates (Template) can use. It is also responsible for the creation and caching of templates (Template) instances. Configuration is actually an instance of a Freemarker.template.Configuration object that is created using its constructor. Typically, a single instance configuration object that uses a share is applied.

The Configuration object can be used by the method of the template object, and each template instance is associated with a Configuration instance, which is associated with the template constructor. Usually you use this method to configuration.gettemplate get the template object.

Shared variables

Shared variables are those that are defined for use by all templates (Template). You can add shared variables by configuration The object's Setsharedvariable method.

Configuration cfg = new Configuration (); ... cfg.setsharedvariable ("Wrap", New wrapdirective ()); Cfg.setsharedvariable ("Company", "Foo Inc"); Using Objectwrapper.default_wrapper

All of the template instances associated with the configuration object can obtain the string by acquiring the To_upper converter, so you do not need to add these variables to root again and again. If you add a variable with the same name to root, your newly added variable will overwrite the previously shared variable.

Warning!

If the configuration object is called by multithreading, do not use the Templatemodel implementation class as a shared variable because they are not thread-safe, as is the case for a servlet-based Web site.

Configuration object initialization already contains some shared converter variables:

Name 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 those named parameters that can affect the behavior of the Freemarker run. such as Locale,number_format.

The configuration parameter is stored in the configuration instance, and it can be modified by the template instance (Template). For example, if you set locale equal to "en_US" in configuration, all template objects will be used, "en_US" unless you modify the default configuration using the SetLocale method in a single template instance. Therefore, the parameters set by configuration can be treated as default parameters, which can be overridden by parameters set at template level, and the parameter information set by them can be overridden by parameters set in the environment (that is, template file directives set) as follows:

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


This type of invocation can be imagined as 3 layers (Configuration object layer, template layer, running environment layer) The following table shows each layer's setting for the parameter:

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 result of the configuration parameters is: A = 1, B = 2, C = 3, D = 1, E = 2. And the F parameter is likely to be null.

If you want to query the list of parameters that you can set, you can refer to the following two sections of the Freemarker API documentation:
Configuration of all Tiers

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


Configuration of the coniguration layer

Freemarker.template.Configuration.setSetting (string,string)


Load Template


Stencil Loader

The template loader is the object that loads the original data based on the abstract path ("INDEX.FTL" or "PRODUCTS/CATALOG.FTL"), and exactly what resource is loaded (the file data in the directory or the data in the database) depends on the specific loader implementation. When you call Cfg.gettemplate, Freemarker will ask you the template loader that was configured to the configuration object, and the template loader is responsible for loading the file.

Built-in template Loader
You can use the following three methods to set the template to load three ways

void Setdirectoryfortemplateloading (File dir);


Or

void Setclassfortemplateloading (Class cl, String prefix);


Or

void Setservletcontextfortemplateloading (Object servletcontext, String path);


The first method shown above specifies a directory in a file system, Freemarker will record the template in this directory, needless to say, this directory must exist, no exception will be thrown.

The second method takes a class as an input parameter, when you want to use ClassLoader to load the template, you can use this method, this way will be called to look for template files, and this template is loaded in a more stable way than the previous one, especially in the production system. You can easily package resource files, icons, and so on to the. jar file.

The third way is to use the context of the Web application as well as the base path (relative to the Wen-inf parent Lu Jin) as parameters. This way the template loader will load the template from the Web application context.

Loading templates from multiple locations

If you want to load templates from multiple locations, you can create a single template loader that corresponds to a different location, and then wrap them into a multitemplateloader template loader, which ultimately passes the method Settemplateloader ( Templateloader loader) Set it to the configuration object, here is an example of loading a template from two different locations:


Freemarker will first search the template file in the path/tmp/templates, if not found then return to the path/usr/data/templates search, if not found, then will try to load in class-loader way.

Get template files from other resources

If none of these built-in template loaders meet your requirements, then you can customize a template loader, simply implement the Freemarker.cache.TemplateLoader interface, and then pass the method Settemplateloader ( Templateloader loader) to pass it to the configuration object.

Cache templates

The Freemarker cache template means that when you get a template through the GetTemplate method, Freemarker not only returns a template object, but also caches the object, and when you next request the template with the same path, It returns the template object in the cache. If you change the template file, then the next time you get the template, Freemarker will automatically reload, reparse template. However, 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 Freemarker how long to judge the version of a template, the default setting is 5 seconds, that is, each 5 seconds will determine whether the template has been modified, if you want real-time judgment, then set the parameter to 0. Another point to note is that not all loaders support this type of judgment, for example, the Class-loader template loader will not find that you have modified the template file.

You can use the Configuration object method Cleartemplatecache to manually clear the template object in the cache for the template Freemarker deletion in the cache. In fact, the cache portion can be added as a build into the freemarker (that is, it can use a third-party caching scheme) You can do this by setting the Cache_storage parameter. It is enough for most developers to freemarker their own freemarker.cache.MruCacheStorage implementations. This cache uses the 2-level most recently Used (most recently used) policy. At the first level, all cache entries are made with strong references (strongly referenced: entries are not understood by the JVM, their relative weak references softly reference) until the maximum time is reached, and the least recently used entries are migrated to level two caches. Entries at this level use weak references until they reach expiration. If the size of the referenced and strongly referenced area 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 this:

Cfg.setsetting (Configuration.cache_storage_key, "strong:20, soft:250");


When you create a new configuration, it defaults to the Mrucachestorage cache implementation and the default value maxstrongsize equals 0,maxsoftsize equals Integer.max_value (that is, the theoretical maximum). However, for high load systems, we recommend that Maxstrongsize be set to a value other than 0, or else it will cause frequent reloading and reparse of the template.

Exception handling

Exceptions that may occur

The exceptions generated by Freemarker can generally be grouped into the following categories:

the exception that is generated during the initialization phase of the Freemarker: it is usually only necessary to initialize Freemarker once in your application, and when the exception generated in this time period is called an initialization exception.

load Parsing template period Exceptions : When you get the template through the Configuration.gettemplate () method (if the template is not previously cached), two types of exceptions are generated:

IOException: Because the template is not found, or in the reading template when there are other IO exceptions, such as you do not read the permissions of the file, etc. freemarker.core.ParseException because the template file syntax is not used correctly;

exception during execution: when you call Template.process (...) method, two class exceptions are thrown:

IOException errors that occur when writing data to output; freemarker.template.TemplatException Other runtime exceptions, such as one of the most common errors is that the template references a nonexistent variable;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.