Apache Velocity
Apache Velocity
is a Java-based template engine, often utilized for
generating web pages using the
Model-View-Controller (MVC) model. However, it has wider uses,
with my particular interest being in generating JSON, HTML and
Java code.
Most of the following example programs utilize
Velocity template files, which
use the extension "vm".
‣ Basics
- VTLTests.java and
vtl.vm: various VTL
(Velocity Template Language) features,
including variables, set, lists, maps, if, and foreach.
- ObjMacro.java,
prods.vm, and
Product.java:
utilizes a simple macro and a list of Product objects.
- VTLCatch.java and
template1.vm.
Most of these examples deal handle errors by simply throwing
Exception. This code employs try-catch blocks,
and also illustrates the use of properties.
‣ Dynamic Templates
Dynamic templates are created at run-time by evaluating
Java strings, so don't require a separate vm file.
‣ Velocity Tools
Velocity's tools are described
here.
‣ Using XML
XML is supported using the
JDOM library.
‣ Using JSON
Velocity offers a JsonTool which relies on the
json-simple
library available at
Clifton Labs.
The first two examples show how to use that library to
read and write JSON text without the aid of Velocity. Only
the third example requires JsonTool.
‣ HTML Generation
- GenHTML.java and
html.vm:
generates HTML based on title and body
text supplied on the command line. The document is saved
in a file called <title>.html.
- MakeTable.java and
prodsTable.vm:
saves a page in ProdsTable.html containing
a table of products extracted from a list of
Product objects.
‣ Java Generation
- GenClass.java and
jclass.vm:
generates a Java class whose name comes from
the first command line argument, while any other
arguments are treated as a series of field names and
types that become private fields and get/set methods.
- JSimple.java,
jsimple.vm, and
JSimp1.txt:
converts 'simplified' code like that promoted
by JEP 445 into a complete Java class.
The code is read from a text file, which can consist of
one-line declarations, functions enclosed between
func and end keywords, and a main
body that starts after the keyword main.
Downloads and Other Links
Dr. Andrew Davison
E-mail: ad@coe.psu.ac.th
Back to the third-party libraries page