HelloWorld----Velocity应用

本地应用velocity
1、建一个工程,把包导入(这里应用的1.6)
2、创建一个含有main方法的类
import java.io.IOException;
import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

public class TestTemplateTheory {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		try {
			//初始化velocity引擎
			VelocityEngine ve = new VelocityEngine();
			ve.init();
			
			//獲取模板
			Template template = ve.getTemplate("test1.vm");
			
			//填充數據
			VelocityContext velocityContext = new VelocityContext();
			velocityContext.put("myname", "姚明");
			velocityContext.put("yourname", "麦迪");
			
			//合并數據
			StringWriter writer = new StringWriter();
			template.merge( velocityContext, writer );
			//顯示
			System.out.println(writer.toString());
			System.out.println(template);
		} catch (ResourceNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MethodInvocationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}


3、和main类同一个目录下见一个模板文件test1.vm
内容如下
<html>
	<body>
		#set($foo = "velocity")
		Hello $foo world;
		My name is $myname
		Your name is $yourname
	</body>
</html>

4、运行main方法,控制台会打印出生成的html内容
<html>
<body>
Hello velocity world;
My name is 姚明
Your name is 麦迪
</body>
</html>

你可能感兴趣的:(apache,html,velocity)