Velocity 官方实例学习一 (app_example1)

刚接触模板语言,主要是想通过模板自动生成一些具有共性的代码块,让自己的开发效率有所提升,因为公司的SSH框架形成了一套固定的模式,我的想法是通过模板,把每次开发中需要的界面可以自动的生成,自己更多关心逻辑业务的编写。

Velocity的使用入门看了下Example感觉确实很比较容易上手,很适合目前的想法。

Example.java

public class Example {
	public Example(String templateFile) {
		try {
			/*
			 * setup
			 */
			//创建Propertis对象,可用properties文件保存
			Properties p = new Properties();
			// 设置输入输出编码类型
			p.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
			p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
			// 初始化模板文件的加载路径 缺省是使用文件系统读取模板文件 模板路径需要放置于class/                        //src目录下
			p.setProperty("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
			//p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, Example.class.getClassLoader().getResource("").getPath());
			Velocity.init(p);

			//数据填充对象
			VelocityContext context = new VelocityContext();
			context.put("list", getNames());

			//模板对象
			Template template = null;

			try {
				template = Velocity.getTemplate(templateFile);
			} catch (ResourceNotFoundException rnfe) {
				System.out.println("Example : error : cannot find template "
						+ templateFile);
			} catch (ParseErrorException pee) {
				System.out.println("Example : Syntax error in template "
						+ templateFile + ":" + pee);
			}

			//输出流
			BufferedWriter writer = writer = new BufferedWriter(
					new OutputStreamWriter(System.out));

			if (template != null)
				template.merge(context, writer);

			/*
			 * flush and cleanup
			 */

			writer.flush();
			writer.close();
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	public ArrayList getNames() {
		ArrayList list = new ArrayList();

		list.add("ArrayList element 1");
		list.add("ArrayList element 2");
		list.add("ArrayList element 3");
		list.add("ArrayList element 4");

		return list;
	}

	public static void main(String[] args) {
		String templateFilePath = "template/example.vm";
		Example t = new Example(templateFilePath);
	}
}
example.vm
##设置一个值为“Velocity”的变量 $this
#set( $this = "Velocity")

##取值 或者${this}
$this is great!

##遍历一个List
#foreach( $name in $list )
    $name is great!
#end

#set( $condition = true)

##条件控制
#if ($condition)
    The condition is true!
#else
    The condition is false!
#end

转载于:https://my.oschina.net/liujiaxing/blog/115875

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值