velocity入门例子

(1)添加依赖

                在maven中添加velocity依赖:

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


(2)创建模板

                创建模板first.vm:

<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
</head>  
    Hello $name,this is my first velocity demo.
</body>  
</html> 
             vm的绝对路径为:D:\code\learn\my-app\first.vm

(3)java实例

package velocity;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Properties;

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;

public class VelocityTest {

	@Test
	public void test() throws IOException {
		String vmPath = "D:\\code\\learn\\my-app\\";
		Properties p = new Properties();
		//指定所有vm文件所在的文件夹路径
		p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, vmPath);
		p.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
		p.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
		p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
		VelocityEngine engine = new VelocityEngine(p);

		String tempName = "first.vm";
		Template template = engine.getTemplate(tempName);

		VelocityContext context = new VelocityContext();
		context.put("name", "luciffer");

		Writer writer = new StringWriter();
		template.merge(context, writer);
		writer.flush();
		System.out.println(writer.toString());
	}

}

              结果为:

<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
</head>  
    Hello luciffer,this is my first velocity demo.
</body>  
</html> 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值