java模板引擎生成html_使用VelocityEngine模板引擎生成HTML

1.依赖jar包

org.apache.velocity

velocity

1.7

2.准备PersonTemplet.vm文件

Personnel information

Dear :

Please notify that Personnel information for $name

name: $name

age: $age

Best Regards

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 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 emailMap = new HashMap();

emailMap.put("name", "zhangsan");

emailMap.put("age", "23");

//模板所在路径+名称

String str = MailContentVelocityRender.render(emailMap, "PersonTemplet.vm");

System.out.println(str);

}

}

控制台输出如下

27fe5d76d88b8b91edb143d904b40d08.png

如果报错

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值