Velocity Template Hello World
Apache Velocity is an open source software project which is hosted by Apache Software Foundation. This template engine provides a template language based on java to reference objects defined in Java code. It basically aims to keep clean separation between view tier and model tiers in a Web based application (in MVC design pattern). Below is sample code which will render velocity template file and print Hello World on the console.
- Maven Project structure:
- pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javahonk</groupId> <artifactId>SendEmailVelocityTemplate</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SendEmailVelocityTemplate Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency> </dependencies> <build> <finalName>SendEmailVelocityTemplate</finalName> </build> </project>
- HelloWold.vm template:
<!DOCTYPE html> <html> <body> <h1>Velocity Template $helloWorld </html>
- VelocityTemplateHelloWorld.java:
package com.javahonk; import java.io.StringWriter; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; public class VelocityTemplateHelloWorld { public static void main(String[] args) { VelocityEngine ve = new VelocityEngine(); ve.init(); Template t = ve.getTemplate("./src/main/resources/templates/HelloWorld.vm"); VelocityContext vc = new VelocityContext(); vc.put("helloWorld", "Hello World!!!"); StringWriter sw = new StringWriter(); t.merge(vc, sw); System.out.println(sw); } }
- Output:
- For more details on Apache Velocity please read it official tutorial here
Download project: SendEmailVelocityTemplate