use*_*555 6 java apache velocity
有人可以解释一下,什么是Apache Velocity?它的目的是什么?
提供一个例子会很好.
提前致谢.
Mar*_*erg 27
Apache Velocity是一个模板引擎.这意味着您可以向上下文添加变量,加载引用这些变量的模板,并从此模板呈现文本,其中变量的引用将替换为变量的实际值.
它的目的是将设计和静态内容与代码分开.以一个网站为例.你不想在你的java代码中创建HTML,对吗?每次更改设计时都需要重新编译应用程序,并且会使用不必要的设计混乱来修改代码.您宁愿想要获取您的变量,无论是计算的还是来自数据库或其他任何变量,并让设计人员创建一个使用变量的HTML模板.
一些伪代码说清楚:
/* The user's name is "Foo" and he is of type "admin"*/
User user = getUserFromDatabase("Foo");
/* You would not add hard coded content in real world.
* it is just to show how template engines work */
String message = "Hello,";
Velocity.init(); /* Initialises the Velocity engine */
VelocityContext ctx = new VelocityContext();
/* the user object will be available under the name "user" in the template*/
ctx.put("user",user);
/* message as "welcome" */
ctx.put("welcome",message);
StringWriter writer = new StringWriter();
Velocity.mergeTemplate("myTemplate.vm", ctx, writer);
System.out.println(writer);
Run Code Online (Sandbox Code Playgroud)
现在给出一个名为myTemplate.vm的文件
${welcome} ${user.name}!
You are an ${user.type}.
Run Code Online (Sandbox Code Playgroud)
输出将是:
Hello, Foo!
You are an admin.
Run Code Online (Sandbox Code Playgroud)
现在让我们假设平面文本应该是HTML.设计者会将myTemplate.vm更改为
<html>
<body>
<h1>${welcome} ${user.name}</h1>
<p>You are an ${user.type}</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
所以输出将是一个html页面,没有 java代码中的单一更改.
因此,使用像Velocity这样的模板引擎(还有其他人,例如Thymeleaf或Freemarker)可以让设计师完成设计师的工作,程序员可以完成程序员的工作,同时对彼此的干扰最小.
| 归档时间: |
|
| 查看次数: |
5985 次 |
| 最近记录: |