使用velocity生成模板

主要的思路分为几步:

  1. 处理数据
  2. 将变量值填充到模板中
  3. 保存为文件
  4. 了解velocity语法

实现代码如下:

Content和MailHead都是实体类,contentTemplate是模板的名称

public void generateAttachment(String attachDir,String contentTemplate,String destFileName,
			List<Content> contents,MailHead mailHead){
		String localFilePath = attachDir+ File.separator + destFileName+".doc";
		FileUtil.createFolderIfNotExists(attachDir);
		VelocityEngine ve = initVelocityEngine();
		VelocityContext context = new VelocityContext();
		context.put("contents", contents);
		context.put("metaInfo", mailHead) ;
		// 生成附件文件的模板
		String emailTemplate = contentTemplate + ".vm";
		Template t = ve.getTemplate(emailTemplate);
		StringWriter writer = new StringWriter();
		t.merge(context, writer);
		String attachContent = writer.toString();
		FileUtil.saveAsFile(localFilePath, attachContent);
	}

初始化VelocityEngine对象的代码如下: 

private VelocityEngine initVelocityEngine() {
		VelocityEngine ve = new VelocityEngine();
		Properties prop = new Properties();
		prop.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
		prop.setProperty(Velocity.INPUT_ENCODING, "GBK");
		prop.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
		prop.setProperty("resource.loader", "class");
		prop.setProperty("class.resource.loader.class",
				"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");

		ve.init(prop);
		return ve;
	}

 将String类型的内容,保存为文件:

public static void saveAsFile(String file, String content) {

		FileWriter fwriter = null;
		try {
			fwriter = new FileWriter(file);
			fwriter.write(content);
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			try {
				fwriter.flush();
				fwriter.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值