有关Velocity语法等知识可以在给出的Velocity学习资源中查看,本文仅简要介绍用Maven创建Velocity工程样例。

##Velocity是什么?
Velocity是一个基于java的模板引擎(template engine)。 起初学习Velocity是为了写网站前台的需要,但Velocity的作用绝不止于此,其还可以从模板中产生SQL、XML、类等。例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 
//以下代码参阅 http://www.ibm.com/developerworks/cn/java/j-lo-velocity1/index.html
public class ${classNameUpCase}Action extends BaseAction{
     @Autowired
     public ${classNameUpCase}Dao ${classNameLowCase}Dao;
     private List<${classNameUpCase}> ${classNameLowCase}s;
     private ${classNameUpCase} ${classNameLowCase};
#foreach ($attr in ${attrs})
     private ${attr[0]} ${attr[1]};
#end
     public String ${classNameLowCase}List() {
          ${classNameLowCase}s = ${classNameLowCase}Dao.retrieveAll${classNameUpCase}s();
          return "${classNameLowCase}List.jsp";
     }
    
    ……

#foreach ($attr in ${attrs})
     #set($attrName = ${attr[1]})
     #set($AttrName = "#toUpperCase($attrName)")
     public ${attr[0]} get${AttrName}() {
          return ${attr[1]};
     }

     public void set${AttrName}(${attr[0]} ${attr[1]}) {
          this.${attr[1]} = ${attr[1]};
     }
#end

    …… 
    
     public void set${classNameUpCase}(${classNameUpCase} ${classNameLowCase}) {
          this.${classNameLowCase} = ${classNameLowCase};
     }
}

##Velocity的学习资源
Velocity官网:http://velocity.apache.org/
很好的博客:Velocity文档1Velocity文档2Velocity文档3

##使用Maven创建Velocity工程 1,在 Eclipse 中点击 File->New->Maven Project
 选中 Create a simple project( skip archetype selection)
 点击 Next

2, 填写Maven项目坐标,点击 Finish。例如

 
Group Id:com.test   
Artifact Id:velocity   
Version:0.0.1-SNAPSHOT   
Packaging:jar   

3,在 src/main/ 目录下创面 webapp 目录

4,右键项目名称,选择 Properties
 选择左边的 Project Facets
 点击右侧 Convert to faceted form…
 选中 Dynamic Web Module和JavaScript
 点击下方 Further configuration available…
 将 Content directory 改为 /src/main/webapp/
 选中下方的 Generate web.xml deployment descriptor
 依次点击 OKApplyOK

5,修改POM文件,添加Velocity依赖包和jetty运行插件,修改为如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0</modelVersion>
     <groupId>com.test</groupId>
     <artifactId>velocity</artifactId>
     <version>0.0.1-SNAPSHOT</version>
     <dependencies>
          <dependency>
               <groupId>org.apache.velocity</groupId>
               <artifactId>velocity</artifactId>
               <version>1.7</version>
          </dependency>
          <dependency>
               <groupId>org.apache.velocity</groupId>
               <artifactId>velocity-tools</artifactId>
               <version>2.0</version>
          </dependency>
     </dependencies>
     <build>
          <plugins>
               <!-- Maven Jetty Plugin -->
               <plugin>
               <groupId>org.mortbay.jetty</groupId>
               <artifactId>maven-jetty-plugin</artifactId>
               <version>6.1.10</version>
               <configuration>
                    <!-- 每2秒的间隔扫描一次,实现热部署 -->
                    <scanIntervalSeconds>2</scanIntervalSeconds>
               </configuration>
               </plugin>
          </plugins>
     </build>
</project>

6,在webapp目录下增加templates/index.vm文件,内容如下

 
<html>  
     <head><title>Sample velocity page</title></head>  
     <body style="text-align:center">
          <h2>Hello Velocity</h2>
          <ul>
          #foreach ($name in $theList)
               <li>$name</li>
          #end  
          </ul>
     </body>  
</html>  

7,在/src/main/java中增加新的package为velocityHandler,在velocityHandler下增加HelloHandler.java,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
 
package velocityHandler;

import java.util.Properties;
import java.util.Vector;

import javax.servlet.ServletConfig;
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.tools.view.VelocityViewServlet;

public class HelloHandler extends VelocityViewServlet {
     private static final long serialVersionUID = 1L;
     private VelocityEngine velo;

     @Override
     public void init(ServletConfig config) throws ServletException {

          super.init(config);
          // velocity引擎对象
          velo = new VelocityEngine();

          // 设置vm模板的装载路径
          Properties prop = new Properties();
          String path = this.getServletContext().getRealPath("/");
          prop.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path + "\\templates\\");

          try {
               // 初始化设置,下面用到getTemplate("*.vm")输出时
               // 一定要调用velo对象去做,即velo.getTemplate("*.vm")
               velo.init(prop);
          } catch (Exception e1) {
               e1.printStackTrace();
          }
     }

     @SuppressWarnings("unchecked")
     @Override
     protected Template handleRequest(HttpServletRequest request,
                    HttpServletResponse response, Context ctx) {
          String p1 = "Hoffman";
          String p2 = "Song";
          @SuppressWarnings("rawtypes")
          Vector personList = new Vector();
          personList.add(p1);
          personList.add(p2);

          ctx.put("theList", personList); // 将模板数据 list放置到上下文环境context中

          try {
               return velo.getTemplate("index.vm");
          } catch (Exception e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          }
          return null;
     }
}

8,修改WEB-INF/web.xml文件为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 
<?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"
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-maven</display-name>
     <welcome-file-list>
          <welcome-file>index.html</welcome-file>
          <welcome-file>index.htm</welcome-file>
          <welcome-file>index.jsp</welcome-file>
          <welcome-file>default.html</welcome-file>
          <welcome-file>default.htm</welcome-file>
          <welcome-file>default.jsp</welcome-file>
     </welcome-file-list>
     <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>index</servlet-name>
          <servlet-class>velocityHandler.HelloHandler</servlet-class>
     </servlet>
     <servlet-mapping>
          <servlet-name>index</servlet-name>
          <url-pattern>/index</url-pattern>
     </servlet-mapping>
</web-app>

9,进入项目根目录,运行

 
$ mvn jetty:run

在浏览器中输入 http://localhost:8080/velocity/index 即可查看结果


说明:本样例源码在https://github.com/xshaun/xshaun.github.io/tree/velocity-0.0.1-SNAPSHOT