使用velocity生成模板

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_23888451/article/details/80534984

主要的思路分为几步:

  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();
			}
		}
	}

猜你喜欢

转载自blog.csdn.net/qq_23888451/article/details/80534984