1、velocity简介:
     velocity是一个java模板引擎技术,任何人可以使用这种简单而又强有力的模板语言去获取java对象。
  在使用Velocity进行web开发时,web开发人员和java程序员可以同时根据Model-View-Controller(MVC)模型,进行网站开发,这也意味着web开发人员可以纯粹的专注于创建看起来好看的网页而程序员可专门编写完美的代码。Velocity使的Java代码从web网页中分离出来,使的web站点在其生命周期中更易于维护,并提供了一种可行的替代Java Server pages(jsp)或PHP的方法。
  Velocity的用处远不止于web范围的应用,例如,它可以用于从模板生成SQL、PostScript和XML。它可以用作生成源代码和报告的独立工具,也可以作为其他系统的集成组件使用。例如,Velocity为各种web框架提供模板服务,使其能够根据一个真正的MVC模型为web应用程序开发提供一个视图引擎。
  Velocity是Apache Software Foundation的一个项目,其负责创建和维护与Apache Velocity引擎相关的开源软件。在Velocity项目中创建的所有软件都可以在Apache software License下使用,并且可以免费向公众开放。

2、velocity第一个简单示例:

转自 http://blog.csdn.net/wangxin1982314/article/details/51234766,纯用于学习   开发环境 eclipse、tomcat、new java project

2.1HelloHandler.java

                            package com.velocitydemo.velocityhandler;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.tools.view.VelocityViewServlet; public class HelloHandler extends VelocityViewServlet {
//在服务器启动的时候构造方法就行了
public HelloHandler(){
System.out.println("构造方法执行");
}
private static final long serialVersionUID = 1L;
private VelocityEngine velo;
//在服务启动的时候init()方法执行
public void init() throws ServletException {
//1.创建Velocity引擎对象
velo = new VelocityEngine();
Properties prop = new Properties();
//path值: D:\Program Files\apache-tomcat-7.0.78 - DemoSys\webapps\velocity-demo\
String path = this.getServletContext().getRealPath("/");
System.out.println("path--->"+path);
//2.设置vm模板的装载路径
prop.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path + "templates/");
prop.setProperty(VelocityEngine.ENCODING_DEFAULT, "UTF-8");
prop.setProperty(VelocityEngine.INPUT_ENCODING, "UTF-8");
prop.setProperty(VelocityEngine.OUTPUT_ENCODING, "UTF-8");
try {
/*
*Velocity引擎对象初始化设置:下面用到getTemplate("*.vm")输出时;一定要调用velo对象去做,即velo.getTemplate("*.vm")
*/
velo.init(prop);
} catch (Exception e1) {
e1.printStackTrace();
}
} protected Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context ctx) {
System.out.println("handleRequest--->执行");
String p1 = "zhangsan";
String p2 = "pangshaoyun";
//3.1创建Vector对象,并把数据放入到该对象
Vector personList = new Vector();
personList.addElement(p1);
personList.addElement(p2);
//3.2或者:将数据放入到List中
List tempList = new ArrayList();
tempList.add("list1");
tempList.add("list2");
List studList = new ArrayList();
studList.add(new Student("123", "Guangzhou"));
studList.add(new Student("456", "Zhuhai")); //4.1ctx.put()表示:把数据填入上下文 Context表示: velocity的上下文context
ctx.put("theList", personList);
ctx.put("temp", tempList);
ctx.put("students", studList);
Template template=null;
try {
//5.1 取得velocity的模版
template = velo.getTemplate("hello.vm");
} catch (ResourceNotFoundException e) {
System.out.println("Example : error : cannot find template " + "hello.vm");
} catch (ParseErrorException e) {
System.out.println("Example : Syntax error in template " + "hello.vm" + ":" + e);
} catch (Exception e) {
e.printStackTrace();
}
//6.1 创建输出流
StringWriter writer = new StringWriter();
//6.2 转换输出,可在前台进行显示
if(template!=null){
try {
template.merge(ctx, writer);
} 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();
}
}
//6.3 在控制台进行显示
System.out.println(writer.toString());
//5.2 在前台页面进行显示
return template;
}
}

2.2 hello.vm文件

<html>
<head>
<title>Hello Velocity</title>
</head>
<body bgcolor="#ffffff">
<center>
<h2>Hello My First Velocity</h2>
<table width="100" cellpadding="5" cellspacing="1" bordercolor="#333333">
<tr>
<td bgcolor="#eeeeee" align="center">name list</td>
</tr>
#foreach ($name in $theList)
<tr>
<td bgcolor="#6666FF" align="center">$name</td>
</tr>
#end #foreach ($temp in $temp)
<tr>
<td bgcolor="#6666FF" align="center">$temp</td>
</tr>
#end #foreach ($s in $students)
<tr>
<td bgcolor="#6666FF" align="center"><$velocityCount>Address: $s.address</td>
</tr>
#end
</table>
</center>
</body>
</html>

2.3 web.xm

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>velocity-demo</display-name>
<servlet>
<servlet-name>velocity</servlet-name>
<servlet-class>org.apache.velocity.tools.view.VelocityViewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>velocity</servlet-name>
<url-pattern>*.vm</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.velocitydemo.velocityhandler.HelloHandler</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

最新文章

  1. 我的Sharepoint视图的使用
  2. Google 谷歌网页搜索, 学术搜索
  3. web前端基础篇③
  4. oracle 临时表空间
  5. EXTJS 资料 Ext.Ajax.request 获取返回数据
  6. [Akka]发送一条消息的内部流程
  7. Linq保留字含义
  8. hdu 1548 A strange lift (bfs)
  9. 源码中的哲学——通过构建者模式创建SparkSession
  10. MonolithFirst
  11. Eclipse设置类,方法注释模版
  12. shiro源码篇 - shiro的session创建,你值得拥有
  13. Feign使用Hystrix
  14. adb 架构
  15. 学习magento要学哪些知识
  16. 在初学Flask中遇到的小问题。
  17. Memcached 集群架构方面的问题
  18. dojoConfig包的配置(7/26号夜)
  19. 利用FPGA实现PCI总线接口及Windows驱动实现
  20. Linux下恢复误删文件:思路+实践

热门文章

  1. leetCode练题——38. Count and Say
  2. 计算机基础 - 动态规划、分治法、memo
  3. 使用阿里的EasyExcel遇到的一些坑(NoSuchMethodError异常)
  4. 【快学SpringBoot】Spring Cache+Redis实现高可用缓存解决方案
  5. 样式计算的几种方式与兼容写法:getComputedStyle&amp;currentStyle&amp;style
  6. 原生js的表单验证
  7. dp-简单迷宫捡金币
  8. vue 项目中的less
  9. 「AT4741 [ABC132D] Blue and Red Balls」
  10. HTML常用标签效果展示