Often you'll want to use a single servlet to handle many different kinds of requests. Also, you'd like a servlet to notice when its template(s) are changed. Classes implementing the interface TemplateCache handle both these problems by maintaining a self-updating cache of compiled templates. The getTemplate() method accepts a string representing the unique name of a template, and returns a Template object. Implementations of TemplateCache might load templates from a filesystem, a database, or a server.
FreeMarker comes with one implementation of TemplateCache: FileTemplateCache, which loads templates from a filesystem. Specifically, it looks for templates in a single directory and its subdirectories. Given a directory path, the cache assumes by default that all files in the directory are templates; it can optionally be given a filename suffix for templates. Once you call its startAutoUpdate() method, it begins updating itself periodically. The string argument to the getTemplate() method is interpreted as the template's path relative to the cache's root directory, using a forward slash (/) as a separator (this is to facilitate using URL path info to request templates). For example, if a TemplateCache object was made for the directory templates, which contains a subdirectory foo, in which there is a template file called index.html, you would call getTemplate("foo/index.html") to retrieve that template.
TemplateCache objects fire CacheEvents, which your servlet can receive by registering itself as a CacheListener. In particular, this is how your servlet can be notified of any exceptions thrown during the cache's attempted updates. You might want to log these exceptions in a file. See the javadoc documentation for details on CacheListener.
Click here for sample Java code that uses FileTemplateCache.
Previous: Sample Code | Next: Request Variables |