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 Cache
handle
both these problems by maintaining a self-updating cache of compiled templates.
The getItem()
method accepts a string representing the unique
name of a template, and returns a Cacheable
object (normally a
Template
object -- see below). Implementations of
Cache
might load templates from a filesystem, a database,
or a server, by implementing the CacheRetriever
interface.
FM-Classic comes with one implementation of Cache
:
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. If a caching strategy is selected that
requires automatic updated, the cache will automatically begin to update
itself periodically.
The first argument to the getItem()
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 FileTemplateCache
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 getItem("foo/index.html")
to retrieve that template.
If a second argument is specified in a call to getItem()
, this
will determine the type of object to be retrieved. The types that can be
returned depend on the TemplateRegistry
. Three types of object
are registered with the TemplateRegistry
by default:
template
-- returns a Template
object. This is the
default type to be retrieved by the cache.unparsed
-- returns an UnparsedTemplate
object.
This behaves like other Template
objects, but its contents wont be
parsed by FM-Classic.binary
-- returns a BinaryData object. This is useful for
caching other file types, such as images.Cache
objects fire CacheEvent
s, 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: Guestbook | Next: Request Variables |