天下之事,必先处之难,而后易之。

Apache Veloctiy模板引擎示例

首先,如果你对Velocity不是很了解,还是建议你去apache的官方网站上去走走....这是velocity的官网:http://velocity.apache.org/

当然如果你对英文文档不是很感冒,这里也有好的资料:

Velocity 文档(1)
Velocity 文档(2)
Velocity 文档(3)

下面我就正式说说我做的项目啦...

项目结构:

运行"helloWorld.vm"模板效果:

运行"userInfo.vm"模板效果:

运行"emailTemplate.vm"模板效果:

代码部分

测试代码:

/**
 * 
 */
package com.b510.velocity.test;

import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import com.b510.velocity.bean.Mail;
import com.b510.velocity.bean.User;

/**
 * 测试类
 * 
 * @author hongten<br>
 * @date 2013-3-9
 */
public class VelocityTest {

    public static final String HELLO_WORLD_VM_PATH = "vms/helloWorld.vm";
    public static final String USER_INFO_VM_PATH = "vms/userInfo.vm";
    public static final String EMAIL_TEMPLATE_VM_PATH = "vms/emailTemplate.vm";

    public static void main(String[] args) throws Exception {
        sayHelloFromVM(HELLO_WORLD_VM_PATH);
        testUser(USER_INFO_VM_PATH);
        testEmail(EMAIL_TEMPLATE_VM_PATH);
    }

    /**
     * 简单的hello world
     * 
     * @param fileVM
     * @throws Exception
     */
    public static void sayHelloFromVM(String fileVM) throws Exception {
        VelocityEngine ve = new VelocityEngine();
        ve.init();
        Template t = ve.getTemplate(fileVM);
        VelocityContext context = new VelocityContext();
        context.put("hello", "Hello world!!");
        StringWriter writer = new StringWriter();
        t.merge(context, writer);
        System.out.println(writer.toString());
    }

    /**
     * test User
     * 
     * @param fileVM
     * @throws Exception
     */
    public static void testUser(String fileVM) throws Exception {
        VelocityEngine ve = new VelocityEngine();
        ve.init();

        Template template = ve.getTemplate(fileVM);
        VelocityContext velocityContext = new VelocityContext();
        User user = new User();
        user.setEmail("hongtenzone@foxmail.com");
        user.setName("hongten");
        user.setBirthday("1990-11-18");
        velocityContext.put("user", user);
        StringWriter stringWriter = new StringWriter();
        template.merge(velocityContext, stringWriter);

        System.out.println(stringWriter.toString());
    }

    /**
     * test email
     * 
     * @param fileVM
     * @throws Exception
     */
    public static void testEmail(String fileVM) throws Exception {
        VelocityEngine velocityEngine = new VelocityEngine();
        velocityEngine.init();

        Template template = velocityEngine.getTemplate(fileVM);
        VelocityContext velocityContext = new VelocityContext();
        Mail mail = new Mail();
        mail.setContent("2013年腾讯开发者新扶持政策解读及创业机会所在");
        mail.setReceiverMail("hongtenzone@foxmail.com");
        mail.setReceiverName("Hongten");
        mail.setSenderMail("opensns_noreply@tencent.com");
        mail.setSenderName("腾讯开放平台");
        mail.setSenderWebSite("open.qq.com");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        mail.setDate(simpleDateFormat.format(new Date()));
        velocityContext.put("mail", mail);
        StringWriter stringWriter = new StringWriter();
        template.merge(velocityContext, stringWriter);

        System.out.println(stringWriter.toString());
    }
}

实体代码:

/**
 * 
 */
package com.b510.velocity.bean;


/**
 * 用户实体类
 * 
 * @author hongten<br>
 * @date 2013-3-9
 */
public class User {

    /**
     * 用户编号
     */
    private Integer id;
    /**
     * 用户名称
     */
    private String name;
    /**
     * 密码
     */
    private String password;
    /**
     * 生日
     */
    private String birthday;
    /**
     * 邮箱
     */
    private String email;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}

/**
 * 
 */
package com.b510.velocity.bean;

/**
 * 邮件
 * 
 * @author hongten<br>
 * @date 2013-3-9
 */
public class Mail {

    private Integer id;
    /**
     * 发件人
     */
    private String senderName;
    /**
     * 发件人邮箱
     */
    private String senderMail;
    /**
     * 发件人网址
     */
    private String senderWebSite;
    /**
     * 收件人
     */
    private String receiverName;
    /**
     * 收件人邮箱
     */
    private String receiverMail;
    /**
     * 内容
     */
    private String content;
    /**
     * 日期
     */
    private String date;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getSenderName() {
        return senderName;
    }

    public void setSenderName(String senderName) {
        this.senderName = senderName;
    }

    public String getSenderMail() {
        return senderMail;
    }

    public void setSenderMail(String senderMail) {
        this.senderMail = senderMail;
    }

    public String getReceiverName() {
        return receiverName;
    }

    public void setReceiverName(String receiverName) {
        this.receiverName = receiverName;
    }

    public String getReceiverMail() {
        return receiverMail;
    }

    public void setReceiverMail(String receiverMail) {
        this.receiverMail = receiverMail;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getSenderWebSite() {
        return senderWebSite;
    }

    public void setSenderWebSite(String senderWebSite) {
        this.senderWebSite = senderWebSite;
    }

}

/Apache-Velocity-java/vms/helloWorld.vm

##test hello world!

$hello

/Apache-Velocity-java/vms/userInfo.vm

##测试User

A: what's your name?
B: $user.name

A: what's your birthday?
B: $user.birthday

A: what's your email address?
B: $user.email

A: good!

/Apache-Velocity-java/vms/emailTemplate.vm

##测试 email

$mail.senderName message notification
Sender       :   $mail.senderName<$mail.senderMail>        
Date         :   $mail.date
Receiver     :   $mail.receiverName<$mail.receiverMail>

Dear $mail.receiverMail:
$mail.senderName send a message notification as following:

$mail.content

please quick login the $mail.senderWebSite message center and have a look.

                                                      $mail.senderName Team

因为velocity源码中默认的编码为"ISO-8859-1":

 

复制代码
复制代码
# ----------------------------------------------------------------------------
# T E M P L A T E  E N C O D I N G
# ----------------------------------------------------------------------------

 input.encoding=ISO-8859-1
 output.encoding=ISO-8859-1
复制代码
复制代码

 

所以,如果出现乱码我们可以设置velocity的编码格式:

     VelocityEngine velocityEngine = new VelocityEngine();
     velocityEngine.setProperty("input.encoding", "UTF-8");
     velocityEngine.setProperty("output.encoding", "UTF-8");
     velocityEngine.init();

这样就可以解决velocity的乱码问题啦...

 

源码下载:http://files.cnblogs.com/hongten/Apache-Velocity-java.rar

文章来源:http://www.cnblogs.com/hongten/archive/2013/03/09/hongten_apache_velocity.html


posted @   boonya  阅读(8)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
历史上的今天:
2013-09-02 Google地图轨迹回放模拟
2013-09-02 GIS 相关知识扫盲
我有佳人隔窗而居,今有伊人明月之畔。
轻歌柔情冰壶之浣,涓涓清流梦入云端。
美人如娇温雅悠婉,目遇赏阅适而自欣。
百草层叠疏而有致,此情此思怀彼佳人。
念所思之唯心叩之,踽踽彳亍寤寐思之。
行云如风逝而复归,佳人一去莫知可回?
深闺冷瘦独自徘徊,处处明灯影还如只。
推窗见月疑是归人,阑珊灯火托手思忖。
庐居闲客而好品茗,斟茶徐徐漫漫生烟。

我有佳人在水之畔,瓮载渔舟浣纱归还。
明月相照月色还低,浅近芦苇深深如钿。
庐山秋月如美人衣,画堂春阁香气靡靡。
秋意幽笃残粉摇曳,轻轻如诉画中蝴蝶。
泾水潺潺取尔浇园,暮色黄昏如沐佳人。
青丝撩弄长裙翩翩,彩蝶飞舞执子手腕。
香带丝缕缓缓在肩,柔美体肤寸寸爱怜。
如水之殇美玉成欢,我有佳人清新如兰。
伊人在水我在一边,远远相望不可亵玩。

点击右上角即可分享
微信分享提示