O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

9.6. Using a Simple Templating Language

Problem

You need to produce a parameterized message using a template stored in a file.

Solution

Use Jakarta Velocity and store your template in the filesystem. Jakarta Velocity is a straightforward templating engine with a lightweight syntax similar to the expression language introduced in Recipe 9.2. The following Velocity template is used to create an email:

#set( $customer = $subscription.customer )
#set( $magazine = $subscription.magazine )

$customer.firstName,

Your subscription to ${magazine.title} on
$subscription.endDate.  If you are interested in renewing your subscription,
please click on the following URL, and enter your password:

${magazine.baseUrl}/renew?cust=${customer.id}

This template references a Subscription bean bound to the name subscription. This Subscription object has a customer property and a magazine property, and both of these properties are assigned to a local template variable using the #set directive. To render a Velocity template, the engine is initialized using Velocity.init( ) , a VelocityContext is created and populated, and the template is read with a FileReader . The following code renders this template:

import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; // Initialize Velocity Velocity.init( ); // Create a context and put our subscription object into the context VelocityContext context = new VelocityContext( ); context.put("subscription", testSubscription( )); // Create a Reader ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required