您的位置:首页 > 其它

web基础----->模板引擎Velocity的使用(一)

2017-07-14 10:57 344 查看
  Velocity 是一个基于 Java 的模板引擎框架,提供的模板语言可以使用在 Java 中定义的对象和变量上。今天我们就学习一下Velocity的用法。

Velocity的第一个例子

项目的主体是两个文件,文件的位置如下图:



一、在pom中添加Velocity的依赖

<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>


二、HelloVelocity的代码如下:

package com.liuling;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.junit.Test;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* Created by huhx on 2017-07-14.
*/
public class HelloVelocity {
@Test
public void velocity_test_1() {
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();

Template t = ve.getTemplate("template/Hellovelocity.vm");
VelocityContext ctx = new VelocityContext();

// 数据
ctx.put("className", "HelloVelocity");
ctx.put("description", "My first velocity demo.");
ctx.put("date", (new Date()).toString());

List temp = new ArrayList();
temp.add("username");
temp.add("password");
ctx.put("list", temp);

StringWriter sw = new StringWriter();
t.merge(ctx, sw);
System.out.println(sw.toString());
}
}


三、Hellovelocity.vm的内容如下:

#set( $myName = "huhx" )
/**
* @author: $myName
* @date:   $date
* @description: $description
*/
public class $className {
#foreach($name in $list)
private String $name;
#end
}


四、运行的结果如下:

/**
* @author: huhx
* @date:   Fri Jul 14 10:48:46 CST 2017
* @description: My first velocity demo.
*/
public class HelloVelocity {
private String username;
private String password;
}


友情链接

velocity的官方文档:http://velocity.apache.org/engine/devel/user-guide.html

velocity的中文翻译:http://blog.csdn.net/hkendless/article/details/6903627
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: