Load Velocity Template Web Application

Load Velocity Template Web Application

If you are using Apache velocity template in your web application and trying to load template file from class path please see below. I will create small project to show you folder structure then with code to load template:

  • Sample maven project structure:

Load Velocity Template Web Application

  • Code to load properties file:
package com.javahonk.controller;

import java.io.File;
import java.io.StringWriter;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class SpringMVCController {
	
	@RequestMapping(value = "/firstPage")	
	public @ResponseBody String firstPage() {
		
		Properties prop = new Properties();
		String absolutePath=new File(Thread.currentThread().getContextClassLoader().getResource("").getFile()).getParentFile().getParentFile().getPath();
		prop.put("file.resource.loader.path", absolutePath+"/WEB-INF/classes");
		VelocityEngine ve = new VelocityEngine();
		ve.init(prop);
		Template t = ve.getTemplate("/templates/Sample.vm");
		VelocityContext vc = new VelocityContext();	
		vc.put("firstName", "Java Honk!!!");
		StringWriter sw = new StringWriter();
		t.merge(vc, sw);		
		return sw.toString();		
		
	}

}
  • You will also need to include velocity jar in your class path because this project is maven based so I have added below dependency:
<dependency>
	<groupId>org.apache.velocity</groupId>
	<artifactId>velocity</artifactId>
	<version>1.7</version>
</dependency>
  • Output:

Load Velocity Template Web Application

  • For more information on Apache velocity please see its official site here

download  Download Project:  SpringMVCRESTFulService

2 thoughts on “Load Velocity Template Web Application”
  1. This is a great tutorial for real, but the downloaded “.rar” files are corrupted when I try to unzip them.
    Please update the download files.
    Thinks

Leave a Reply

Your email address will not be published. Required fields are marked *