Velocity的应用

     Velocity是一种Java模版引擎技术,该项目由Apache提出,由另外一种引擎技术Webmacro引深而来。那什么是官方的Velocity定义呢?Apache对它的定义是:一种基于Java的模板引擎,但允许任何人使用简单而强大的模板语言来引用定义在Java代码中的对象。在项目开发中,Velocity非常实用,举个简单例子,web中有个功能忘记密码,当点击忘记密码,web网站会自动发送一封邮件到指定的邮箱中。这封邮件就可以采用Velocity模板技术做。非常简单。下面给出一个简单的Velocity例子。

   首先需要导入相关的jar包。commons-collections-3.2.1.jar,commons-lang-2.4.jar,log4j.jar,oro-2.0.8.jar,velocity-1.6.jar。导入相关包后就可以进行开发了。

   在src目录下新建veloctity.properties文件,这是配置文件。给出样例,

runtime.log=E:\\Workspaces\\MyEclipse 10\\Velocity\\test.log
    file.resource.loader.path=E:\\Workspaces\\MyEclipse 10\\Velocity\\vm
    input.encoding=UTF-8
    output.encoding=UTF-8
在配置文件第1行中,值为test.log的绝对路径,第二行中,首先你可以在根目录下新建vm文件夹,然后其值就为vm的绝对路径。第3,4行为输入和输出的编码。

配置好了后,在vm新建helloword.vm文件

${who}说,${content}

里面的语法类似EL语法。

最后新建HelloWord.java类,给模板赋值.

package cn.itcast.velocity;

import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class HelloWorld {

	public static void main(String[] args) {
		try {
			Velocity.init("src/veloctity.properties");
			VelocityContext context = new VelocityContext();
			context.put("who", "黎明");
			context.put("content", "这是我第一个Velocity应用");
			
			Template template = Velocity.getTemplate("helloword.vm");
			StringWriter sw = new StringWriter();
			template.merge(context, sw);
			sw.flush();
			
			System.out.println(sw.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

这样第一个Velocity案例就出来了。


Velocity相关语法:

1.读取类对象Person中的属性数据

${person.name}

2.遍历list中的数据:

List<String> names = new ArrayList<String>();
names.add("第一个");
names.add("第二个");
names.add("第三个");
			
context.put("list", names);

在helloword.vm中读取数据:

#foreach($element in $list)
    ${element}
#end


带序号的迭代:

#foreach($element in $list)
    $velocityCount . $element
#end
默认序号是从1开始,如果想要更改为从0开始,需要在velocity.properties中添加配置

directive.foreach.counter.initial.value=0

这样序号就从0开始。


3.if判断

在Java类中:

context.put("condition", true);

在helloword.vm模板中

#if($condition)
      成立
#else
   不成立
#end

4.map集合取值:

Map<String, Integer> names = new HashMap<String, Integer>();
names.put("a", 1);
names.put("b", 2);
names.put("c", 3);
			
context.put("names", names);

在helloword.vm模板取值:

#foreach($key in $names.keySet())
    $key = $names.get($key)
#end

5.set集合:

#set( $name="老张")
$name

6.写文件到html文件中:

package cn.itcast.velocity;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.print.attribute.standard.MediaSize.Other;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class HelloWorld {

	public static void main(String[] args) {
		try {
			Velocity.init("src/veloctity.properties");
			VelocityContext context = new VelocityContext();
/*	
 * 迭代类对象		
 *          Person person = new Person("小张", 12);
			context.put("who", "黎明");
			context.put("person", person);
*/
			
			
/*			遍历list集合对象
            List<String> names = new ArrayList<String>();
			names.add("第一个");
			names.add("第二个");
			names.add("第三个");
			
			context.put("list", names);
			context.put("who", "黎明");
*/
			
/*
 * if判断
 *          context.put("condition", true);
 */

			/*
			 * Map集合
			Map<String, Integer> names = new HashMap<String, Integer>();
			names.put("a", 1);
			names.put("b", 2);
			names.put("c", 3);
			
			context.put("names", names);
			*/
			
			List<Person> persons = new ArrayList<Person>();
			persons.add(new Person("小明", 1));
			persons.add(new Person("小张", 2));
			persons.add(new Person("小花", 3));
			context.put("persons", persons);
			
			Template template = Velocity.getTemplate("helloword.vm");
			
			File savedir = new File("E:\\Workspaces\\MyEclipse 10\\Velocity\\test.html");
			FileOutputStream outputStream = new FileOutputStream(savedir);
			OutputStreamWriter writer = new OutputStreamWriter(outputStream,"UTF-8");
			BufferedWriter bufferedWriter = new BufferedWriter(writer);
			
			template.merge(context, bufferedWriter);
/*			StringWriter sw = new StringWriter();
			template.merge(context, sw);
			sw.flush();
			System.out.println(sw.toString());*/
			bufferedWriter.flush();
			outputStream.close();
			bufferedWriter.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

在vm模板中:

<html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>人员列表</title>
  </head>
  <body>
    <table width="100">
    <tr>
      <td>人员ID</td>
      <td>姓名</td>
    </tr>
    #foreach ($person in $persons)
    <tr>
      <td>${person.id}</td>
      <td>${person.name}</td>
    </tr>
    #end
    </table>
  </body>
  </html>

效果图如下:




下载链接:http://download.youkuaiyun.com/detail/tan313/9054873


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值