使用VelocityEngine模板引擎生成HTML

参考 velocity模板加载的三种形式   Java使用 VelocityEngine模板引擎快速生成HTML等各种代码

1.依赖jar包

<dependency>
	<groupId>org.apache.velocity</groupId>
	<artifactId>velocity</artifactId>
	<version>1.7</version>
</dependency>

2.准备PersonTemplet.vm文件

<html>
	<head>
		<title>
			Personnel information   
		</title>
	</head>
	<body>
		Dear :<br>
		<br>
			Please notify that Personnel information for $name <br>
			 
			name: $name <br>
			age: $age <br>
        <br>
		Best Regards <br>
	</body>
</html>

3.使用VelocityEngine模板引擎快速HTML 

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

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

public class MailContentVelocityRender {

	public static String render(Map<String, Object> context, String templateName) {

		Properties properties = new Properties();
		//从类路径加载模板文件 设置velocity资源加载方式为class 
		properties.setProperty("resource.loader", "class");  
		//设置velocity资源加载方式为class时的处理类
		properties.setProperty("class.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		properties.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
		properties.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
		properties.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
		properties.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.NullLogChute");
		
		//实例化一个VelocityEngine对象
		VelocityEngine velocityEngine = new VelocityEngine(properties); 
		velocityEngine.init();
		
		//根据template路径 实例化一个Template对象
		Template template = velocityEngine.getTemplate(templateName); 
		
		//实例化一个VelocityContext对象 这个对象中存放要在邮件中显示的参数
		VelocityContext velocityContext = new VelocityContext(context);  		
		//velocityContext.put("age", 22);//也可以向VelocityContext中放入键值
		
		 //实例化一个StringWrite
		StringWriter stringWriter = new StringWriter();
						
		template.merge(velocityContext, stringWriter);
		return stringWriter.toString();
	}

}

4.测试

import java.util.HashMap;
import java.util.Map;

public class App 
{
    public static void main( String[] args )
    {
    	//准备邮件中参数
		Map<String, Object> emailMap = new HashMap<String, Object>();
		emailMap.put("name", "zhangsan");
		emailMap.put("age", "23");
		//模板所在路径+名称
		String str = MailContentVelocityRender.render(emailMap, "PersonTemplet.vm");
		System.out.println(str);
    }
}

控制台输出如下

如果报错

ResourceManager : unable to find resource 'Hellovelocity.vm' in any resource loader.
Exception in thread "main" org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'Hellovelocity.vm'

要把PersonTemplet.vm所在的文件夹 右键文件夹  build path ----use as source folder

posted on 2019-08-04 20:18  dreamstar  阅读(495)  评论(0编辑  收藏  举报