Thursday, 18 August 2016

Velocity Template in java web application

Following is the code to create the text from the velocity template in a java web application.

Properties props = new Properties();
            props.setProperty("resource.loader", "class");
            props.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            props.setProperty("webapp.resource.loader.path", "/WEB-INF/classes");
            VelocityEngine velocityEngine = new VelocityEngine();
            velocityEngine.init(props);
            Template template = velocityEngine.getTemplate("helloworld.vm");
             /* create our list of maps  */
            VelocityContext context = new VelocityContext();
            context.put("name", "jakki");
            /* now render the template into a StringWriter */
            StringWriter writer = new StringWriter();
            template.merge(context, writer);
            /* show the World */
            String content = writer.toString();

Template is as follows.

Hello $name!  Welcome to Dev Code Helper!
 
Dependency JARs
 
velocity-1.4.jar
velocity-dep-1.4.jar 
 

No comments:

Post a Comment