Velocity 可以作为 SpringMVC 的 View 使用,也可以用来生成邮件,静态页面等。
Velocity 模版中可以直接调用对象的方法,这点比 Freemarker 好用,if else foreach 等语句也更舒服。
Gradle 依赖
1 2
| compile 'org.apache.velocity:velocity:1.7' compile 'org.apache.velocity:velocity-tools:2.0'
|
VelocityTest
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.apache.velocity.app.VelocityEngine; import org.junit.Test;
import java.io.StringWriter; import java.io.Writer; import java.util.Properties;
public class VelocityTest { @Test public void generate() { String templateDirectory = "/Users/Biao/view/"; Properties properties = new Properties(); properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, templateDirectory); properties.setProperty(VelocityEngine.INPUT_ENCODING, "UTF-8"); properties.setProperty(VelocityEngine.OUTPUT_ENCODING, "UTF-8"); Velocity.init(properties);
Template template = Velocity.getTemplate("hello.vm");
VelocityContext ctx = new VelocityContext(); ctx.put("name", "Hello"); ctx.put("static", "static path");
Writer writer = new StringWriter(); template.merge(ctx, writer);
System.out.println(writer); } }
|
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <!DOCTYPE html> <html>
<head> <meta charset="utf-8"> <title>REST</title> </head>
<body> Hello 你好!<br> 不存在的属性: $var2<br> 全局变量: static path<br> Context Path: $request.contextPath -- </body>
</html>
|
hello.vm
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <!DOCTYPE html> <html>
<head> <meta charset="utf-8"> <title>REST</title> </head>
<body> $name 你好!<br> 不存在的属性: $!var1 $var2<br> 全局变量: $static<br> Context Path: $request.contextPath -- </body>
</html>
|