liveBook · Manning

Apache Velocity

As explained in Test Driven: Practical TDD and Acceptance TDD for Java Developers

Apache Velocity is a Java-based template engine for generating text by merging templates with supplied data.

Apache Velocity renders templates by combining plain text, variables, and basic conditionals or loops with supplied values. Its independence from Java EE makes it a lightweight option for testing web views outside a container. section 5.3.2 section 5.0

A basic render follows three steps:

  • Create a VelocityContext and add named values. section 5.3.2
  • Initialize a VelocityEngine. section 5.3.2
  • Evaluate the template with the context and write the rendered output to a java.io.Writer. section 5.3.2
String template = "Hello $user";
StringWriter writer = new StringWriter();
VelocityContext context = new VelocityContext();
context.put("user", "Reader");
VelocityEngine engine = new VelocityEngine();
engine.init();
engine.evaluate(context, writer, "test", template);

A minimal example renders “Hello $user” with the value “Reader” supplied in the context. section 5.3.2

A login form

A Velocity template can contain HTML form fields such as j_username and j_password; generated HTML can then be checked with XPath-based test helpers. section 5.3.2

How Test Driven: Practical TDD and Acceptance TDD for Java Developers covers it

How deep it goes
Defines template evaluation and walks through context population and engine evaluation into a Writer.
Examples
Renders “Hello $user” with a Reader value and shows a login form with username and password fields.
What you can do after
Apply Velocity by supplying a context and template, then evaluating the result into a Writer.
How it connects
Connects Velocity with JavaServer Pages, Java EE, web-view testing, and HttpUnit.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Test Driven: Practical TDD and Acceptance TDD for Java Developers. The section links point to the parts of the book it draws on.