您的位置:首页 > 移动开发

Velocity 官方实例学习一 (app_example1)

2013-03-22 00:00 459 查看
刚接触模板语言,主要是想通过模板自动生成一些具有共性的代码块,让自己的开发效率有所提升,因为公司的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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Velocity