一、什么是Velocity及简单示例

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 Filesapache-tomcat-7.0.78 - DemoSyswebappsvelocity-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;
                                }
                            }
View Code

 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>
View Code

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>
View Code
细水长流,打磨濡染,渐趋极致,才是一个人最好的状态。
原文地址:https://www.cnblogs.com/jiarui-zjb/p/8227473.html