velocity简单例子

来源:互联网 发布:php import 编辑:程序博客网 时间:2024/06/06 01:50
导入velocity所依赖的jar文件,在WEB-INF目录下建立.vm的模板,如下:

        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>$title</title>
    </head>
    <body>
        <table border="1">
            <tr>
                <td>velocity</td>
            </tr>
            <tr>
                <td>velocity</td>
            </tr>
            <tr>
                <td>velocity</td>
                $title
            </tr>
            <tr>
                <td>velocity</td>
            </tr>
            <tr>
                <td>velocity</td>
            </tr>
            <tr>
                <td>velocity</td>
            </tr>
            <tr>
                <td>velocity</td>
            </tr>
        </table>
    </body>
</html>
实现类如下:
  package com.gayngyi.velocity;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
public class CreateHtml {
    public static void main(String[] args) {
        try {
            //初始化vm模板
            Template template=Velocity.getTemplate("WebContent\\WEB-INF\\velocityTemp\\test.vm","UTF-8");
            //初始化上下文
            VelocityContext context=new VelocityContext();
            //添加数据到上下文中
            context.put("title", "我的第一个velocity页面");
            //生成html页面
            PrintWriter pw=new PrintWriter("f:\\myvelocity.html");
            template.merge(context, pw);
            //关闭流
            pw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ResourceNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseErrorException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
    }
}

原创粉丝点击