java velocity是什么意思_java – 什么是Apache Velocity?

Apache Velocity是

template engine.这意味着您可以向上下文添加变量,加载引用这些变量的模板,并从该模板呈现文本,其中变量的引用替换为变量的实际值.

它的目的是将设计和静态内容与代码分开.以一个网站为例.你不想在你的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 VerlocityContext();

/* 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);

现在给出一个名为myTemplate.vm的文件

${welcome} ${user.name}!

You are an ${user.type}.

输出将是:

Hello, Foo!

You are an admin.

现在让我们假设平面文本应该是HTML.设计者会将myTemplate.vm更改为

${welcome} ${user.name}

You are an ${user.type}

所以输出将是一个html页面,没有java代码中的单一更改.

因此,像Velocity这样的模板引擎(例如Thymeleaf或Freemarker)的使用让设计师能够完成设计师的工作,程序员可以完成程序员的工作,同时对彼此的干扰最小.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值