1》:以html模板为例: File file = null; file = new File(path+"/template/member_email.html"); if(file != null){ InputStream in = new FileInputStream(file); java.io.BufferedReader breader = new BufferedReader(new InputStreamReader(in, "utf-8")); String currentLine; while((currentLine = breader.readLine()) != null){ htmlCode.append(currentLine); } in.close(); } return htmlCode.toString(); 2》: Velocity.init(); VelocityContext context = new VelocityContext(); context.put("custName", bean.getCustName() != null?bean.getCustName():""); context.put("nickName", bean.getNickName() != null?bean.getNickName():""); context.put("address", bean.getAddress()!=null?bean.getAddress():"");//地址 context.put("call", bean.getCall()!=null?bean.getCall():"");//称谓 context.put("imageUrl", bean.getImageUrl()!=null?bean.getImageUrl():"");//图片路径 context.put("goodsName",bean.getGoodsName()!=null?bean.getGoodsName():"");//商品名称 StringWriter w = new StringWriter(); Velocity.evaluate(context, w, "", body); body = w.toString(); return body; 3》:vm模板文件的内容为: <td><font style="font-size: 14px; font-family: '微软雅黑'; font-weight: bold; color: #333;">亲爱的<font style="margin: 0 5px; color: #fb6104;">$nickName</font>:</font></td> 4》:以vm为例子测试 public static void main(String args[]) throws Exception{ File templateFile = new File("template_velocity.vm"); if(templateFile.exists()){ templateFile.delete(); } templateFile.createNewFile(); FileWriter fw=new FileWriter("template_velocity.vm"); fw.write("We are using $date $name to render this."); fw.close(); //初始化并取得Velocity引擎 VelocityEngine ve = new VelocityEngine(); ve.init(); //取得velocity的模版 Template t = ve.getTemplate("template_velocity.vm"); //取得velocity的上下文context VelocityContext context = new VelocityContext(); //把数据填入上下文 context.put("name", "Liang"); context.put("date", DateUtils.getNow()); //为后面的展示,提前输入List数值 List temp = new ArrayList(); temp.add("1"); temp.add("2"); context.put("list", temp); //输出流 StringWriter writer = new StringWriter(); //转换输出 t.merge(context, writer); System.out.println(writer.toString()); }
任何Velocity的应用都包括模板制作和程序部分两个方面。按照惯例,采用HelloWorld来作为第一个程序的示例。
1. 模板制作模板示例hellosite.vm的内容如下(虽然其不是以HTML为主,但很容易改成一个HTML的页面):
Hello $name! Welcome to $site world!
2.Java程序部分
下面是Java代码:
1.import java.io.StringWriter; 2. import org.apache.velocity.app.VelocityEngine; 3. import org.apache.velocity.Template; 4. import org.apache.velocity.VelocityContext; 5. public class HelloWorld 6. { 7. public static void main( String[] args ) 8. throws Exception 9. { 10. /* first, get and initialize an engine */ 11. VelocityEngine ve = new VelocityEngine(); 12. ve.init(); 13. /* next, get the Template */ 14. Template t = ve.getTemplate( "hellosite.vm" ); 15. /* create a context and add data */ 16. VelocityContext context = new VelocityContext(); 17. context.put("name", "Eiffel Qiu"); 18. context.put("site", "http://www.eiffelqiu.com"); 19. /* now render the template into a StringWriter */ 20. StringWriter writer = new StringWriter(); 21. t.merge( context, writer ); 22. /* show the World */ 23. System.out.println( writer.toString() ); 24. } 25. }
将这两个文件放在同一个目录下,编译运行,结果是:
Hello Eiffel Qiu! Welcome to http://www.eiffelqiu.com world
为了保证运行顺利,请从Velocity的网站http://jakarta.apache.org/velocity/上下载Velocity的运行包,并将其中Velocity Jar包的路径放在系统的Classpath中,这样就可以顺利编译和运行以上程序了。
这个程序很简单,但是它能清楚地说明Velocity的基本工作原理。程序中的其它部分基本上很固定,最主要的部分在以下几段代码。
◆ Velocity获取模板文件,得到模板引用:
1.Template t = ve.getTemplate( "hellosite.vm" );
◆ 初始化环境,并将数据放入环境:
1.VelocityContext context = new VelocityContext(); 2.context.put("name", "Eiffel Qiu"); 3.context.put("site", "http://www.eiffelqiu.com");
◆ 初始化Velocity模板引擎:
1.VelocityEngine ve = new VelocityEngine(); 2.ve.init();
◆ 将环境变量和输出部分结合:
1.StringWriter writer = new StringWriter(); 2.t.merge( context, writer ); 3./* show the World */ 4.System.out.println( writer.toString() );
这一部分在将来的Servlet应用中会有所区别,因为网页输出并不和命令行输出相同,如果用于网页输出,将并不通过System.out输出。
小结
Velocity解决了如何在Servlet和网页之间传递数据的问题,当然这种传输数据的机制是在MVC模式上进行的,也就是View、Modle和Controller之间相互独立工作,一方的修改不影响其它方面的变动。
他们之间的联系通过环境变量(Context)来实现,当然网页制作方和后台程序方要相互约定好对所传递变量的命名,比如上个程序例子中的site、name变量,它们在网页上就是$name、$site。
这样只要双方约定好变量名字,就可以独立工作了。无论页面如何变化,只要变量名不变,后台程序无需改动,前台网页也可以任意由网页制作人员修改。
通常简单变量名无法满足网页制作显示数据的需要,比如经常会循环显示一些数据集,或者是根据一些数据的值来决定如何显示下一步的数据等。
Velocity同样提供了循环、判断的简单语法以满足网页制作的需要。Velocity提供了一个简单的模板语言,供前端网页制作人员使用,这个模板语言简单到大部分懂得JavaScript的人都可以很快掌握,其甚至比JavaScript更简单。
当然这种简单是刻意的,因为不需要Velocity什么都能完成,而只需专注于其应该完成的。View层不应该包含更多的逻辑,Velocity的简单模板语法完全可以满足所有对页面显示逻辑的需要,并且也不会发生像JSP那样因为一个无限循环语句而毁掉系统的情况。
public static void main(String[] args) throws Exception { Map<String,String> map = new HashMap<String,String>(); map.put("id", "123"); map.put("name1", "123"); Velocity.init(); VelocityContext velocityContext = new VelocityContext(map); StringWriter result = new StringWriter(); String sqlTemplate = "select * from where id = $id and name=:name"; // Template template = Velocity.getTemplate(sqlTemplate, "UTF-8"); Velocity.evaluate(velocityContext, result, "", sqlTemplate); // VelocityEngine ve = new VelocityEngine(); System.out.println(result.toString()); }
【收藏地址】http://www.myexception.cn/database/424711.html