Velocity Tutorial

Velocity is used for using templates in the applciation (if there is any other use please tell me and I will add it to the notes).

To start with download velocity from apache's site. You can get velocity.jar from there. Canfigure your IDE to handle the classpaths etc.

Let's say we want to create a template to send mails when a user is created.

1. Create the vsl file (we will use html code in the mails):

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">

<title>Email Text</title>

</head>

<body>

<p><font face="Arial" size="2"><span>A new user "$userName" is created in $ourProduct for $userName.</span></font></p>

<p><font face="Arial" size="2">*** Please do not reply to this email message. Emails sent to this email address are automatically deleted and are not read.***</font></p>

</body>

2. Now create the file which parses the email and puts in the values: (the function is mentioned for reference)

/**
* @param values - It is the hashMap which has the key value pair for the values whcih need to be fed in.
*/

public String build(Map values) {

StringWriter stringWriter = null;

try {
VelocityContext velocityContext = new VelocityContext(values);
Velocity.init();
Template templ = Velocity.getTemplate("templates/email.vsl");

stringWriter = new StringWriter();

templ.merge(velocityContext, stringWriter);
} catch (Exception ex) {
ex.printStackTrace();
}

return stringWriter.toString();
}

Now the above method can be called to create the final text of the email. The value returned is the body of the vsl with the proper values plugged in.

Back To Technicals

1