Java中常用的模板技术有freemarker和valocity,其中freemarker的默认后缀名是.ftl;valocity的默认后缀名是.vm。他们的后缀名都是可以修改的。
- 模板技术的原理都是 模板+数据=文本 这里就只介绍一下valocity的使用方法
一:要使用valocity模板技术首先需要导入valocity模板包
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.6</version>
</dependency>
- 代码实现
首先创建模板应用上下文,存入数据 —拿到相应的模板且设置好编码 —准备输出流 —将模板与数据结合 —最后关闭流
//创建模板应用上下文
VelocityContext context = new VelocityContext();
context.put("msg", "这是数据");
//拿到相应的模板(需要设置好编码)
Template template = Velocity.getTemplate("temptest/hello.html","UTF-8");
//准备输出流
File file = new File("temptest/helloNew.html");
FileWriter writer = new FileWriter(file);
template.merge(context, writer);
writer.close();
- 模板中的操作
1.单行注释 ---》##
2.多行注释 ---》#**#
3.#set()的用法 ---》#set($a="值"):为a设置变量
4判断 ---》#if() ->#else if() -> #else ->#end
5.循环 ---》#foreach($a in $list)