apache Velocity模版引擎--HelloWorld

1. Velocity工作流程

  • 配置并初始化VelocityEngine 或者Velocity(单例)
  • 创建一个context
  • 向context中添加变量
  • 加载Velocity模版
  • Merge 模版和context得到渲染后的结果

Code:

  1. 目录结构


    apache Velocity模版引擎--HelloWorld_第1张图片
    Paste_Image.png
  2. helloworld.vm内容:
$hello
  1. pom:必要的依赖只有一个velocity


    4.0.0

    com.minxin
    apache.velocity
    1.0-SNAPSHOT

    
        
        
            org.apache.velocity
            velocity
            1.7
        
   

  1. java代码
package com.velocity.helloworld;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

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


/**
 * @author mingxin
 */
public class Main {

  public static void main(String[] args){
    Main main = new Main();
    main.useVelocity();
  }

  public void useVelocityEngine(){
    try{
      VelocityEngine ve = new VelocityEngine();
      ve.init(getDefaultProp());
      VelocityContext context = new VelocityContext();
      context.put("hello", "Hello World!");
      StringWriter w = new StringWriter();
      Template t = ve.getTemplate("template/helloworld.vm");
      t.merge(context, w);
      System.out.println("template:" + w);
    }catch (Exception e){
      e.printStackTrace();
    }
  }


  public void useVelocity(){
    try{
      Velocity.init(getDefaultProp());
      VelocityContext context = new VelocityContext();
      context.put("hello", "Hello World!");
      StringWriter w = new StringWriter();
      Template t = Velocity.getTemplate("template/helloworld.vm");
      t.merge(context, w);
      System.out.println("template:" + w);
    }catch (Exception e){
      e.printStackTrace();
    }
  }

  public Properties getDefaultProp(){
    Properties prop = new Properties();
    prop.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    prop.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    return prop;
  }
}

2.遇到的问题

2.1 找不到模版路径

严重: ResourceManager : unable to find resource 'helloworld.vm' in any resource loader.

不管是用VelocityEngine还是用Velocity在init之前都需要配置一下资源加载器。参考解决方法

  public Properties getDefaultProp(){
    Properties prop = new Properties();
    prop.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    prop.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    return prop;
  }

你可能感兴趣的:(apache Velocity模版引擎--HelloWorld)