Velocity Template Engine – Part 2 (Getting templates from a JAR)

In my previous post I described the basics of Velocity template engine. In that post, we were making use of a template (the .vm file) which we keep outside the application archive. But there are some potential issues in doing that – sometimes those file may get corrupted or deleted. So a better idea will be to keep it with in the application archive itself. In this post I will explain how we can make use of a template file with in an archive.

Sample Template Filetestvelocity.vm

Hello $name! Welcome to Velocity!


A java program that refers to the the testvelocity.vm template.

public static void handleTemplate()
	VelocityEngine engine = null;
	String myTemplateBody = null;
	VelocityContext context = null;
	StringResourceRepository repository = null;
	Template template = null;
	StringWriter writer = null;

		// Getting Velocity Engine
		engine = getVelocityEngine(engine);

		// Reading Template Body from the template file(.vm file) in the jar
		myTemplateBody = getTemplateFromJar();

		// Setting the template body in string repository with a template
		// name. Here the template name is used as a key for future mapping.
		repository = StringResourceLoader.getRepository();
		repository.putStringResource("myTemplateName", myTemplateBody);

		// Getting the context with placeholder values
		context = getVelocityContext();

		// Fetch Template to a StringWriter
		template = engine.getTemplate("myTemplateName");
		writer = new StringWriter();
		template.merge(context, writer);

		System.out.println("VM Template:\n" + myTemplateBody);
		System.out.println("Output:\n" + writer.toString());
	catch (Exception e)
		System.out.println("Oops! We have an exception");


Getting the template engine
Velocity supports different kind of resource loaders.  In this context we need to use a String resource loader. Know more about it here.

private static VelocityEngine getVelocityEngine(VelocityEngine engine)
throws Exception
	// Initializes the velocity engine with properties. We should specify
	// the resource loader as string and the class for
	// string.resource.loader in properties
	Properties p = new Properties();

	p.setProperty("resource.loader", "string");
	engine = new VelocityEngine();

	return (engine);

Getting Template file from JAR
Know more about JAR and deployment here.

// Reading the file contents from the JAR
inStream = TestVelocity.class
stringBuilder = new StringBuilder();
streamReader = new InputStreamReader(inStream);
bufferedReader = new BufferedReader(streamReader);

while ((line = bufferedReader.readLine()) != null)

Getting Velocity context

context = new VelocityContext();
context.put("name", "mathew");


Velocity console out

Please check this post get additional information on building a JAR file & executing it: