然后修改conf文件下的server.xml文件,在server.xml里的
           <Connector port="8080" .... />字段后
  增加对GET方法获取数据时的编码设置参数 URIEncoding="GBK"
 增加对Post方法获取数据时的编码设置参数 useBodyEncodingForURI="true"                      即<Connector port="8080" ...URIEncoding="GBK"   useBodyEncodingForURI="true"/>
          若是用Apache Tomcat去运行Web程序,同理也是像上面一样修改。

1.3 修改MySql的编码:
          建议下一个MySql Gui工具,打开MySql adminstrator ,在startup variables

项里的advanced下的Def.char Set里写进GBk。

前言:最近在用velocity开发个东西,但其vm页面的输出总是会乱码,在网上找了很多资料,还是不能解决,最终在一篇网上的文章的启发下,http://www.javaeye.com/post/540300,终于搞定了这个问题。

好,废话少说,下面是解决办法。
            在这里,我的配置是全部采用GBK这种编码,若要采用其他编码,是同理的。我的开发环境是windows XP,MYEclipse6.0,MyEclipse自带的Tomcat,MySql数据库,项目用到 的技术是Velocity+servlet+javaBean。

1.首先要确保开发工具(如MyEclipse),WEB服务器(如Tomcat),数据库 (如  MySql)采用的是同一种编码。

1.1 MyElcipse的配置:
          对着工程项目按右键,点属性-->资源,在text file encoding里选GBK。

1.2 MyEclipse自带的Tomcat的配置:
         强烈建议先装一个Apache Tomcat6.0,再把安装目录下的conf文件夹复制,放到MYEclipse的工程文件里的.data下的.plugins下的   com.genuitec.eclipse.easie.tomcat.myeclipse下的tomcat,把Tomca下的conf覆盖掉。
               注:这是解决MyEclipse自带的Tomcat乱码问题最有效的解决办法。
 
         然后修改conf文件下的server.xml文件,在server.xml里的
           <Connector port="8080" .... />字段后
  增加对GET方法获取数据时的编码设置参数 URIEncoding="GBK"
 增加对Post方法获取数据时的编码设置参数 useBodyEncodingForURI="true"                      即<Connector port="8080" ... URIEncoding="GBK"   useBodyEncodingForURI="true"/>
          若是用Apache Tomcat去运行Web程序,同理也是像上面一样修改。

1.3 修改MySql的编码:
          建议下一个MySql Gui工具,打开MySql adminstrator ,在startup variables

项里的advanced下的Def.char Set里写进GBk。

2.设置velocity的编码设置

2.1 这里有两种方法,网上的文章一般是讲这些。

方法一:修改Veloicity.properties配置文件,加入以下信息
                     input.encoding=GBK  
                     output.encoding=GBk

方法二:写到这里,顺便把velocity经常找不到vm文件的解决方法也加进去了
                  在关键servelt类里定义一个私有对象
              private VelocityEngine velo;       //velocity引擎对象

再在servelt类里的init()方法里加入以下语句去加入一些属性设置                   
            velo = new VelocityEngine();   
           //设置vm模板的装载路径
         Properties prop = new Properties();
         String path = this.getServletContext().getRealPath("/");
                 //"template/" 是指定你的vm文件放在WEBROOT下的template,根据
                 // 你工程的vm文件位置的不同而作相应的变化
        prop.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path + "template/");

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

2.2 接着,就是整个问题解决的关键之处了,在doGet()和doPost()方法的最初加入两条语句
             request.setCharacterEncoding("GBK");
             response.setContentType("text/html;charset=GBK");
       为什么要加入这两句呢?因为Velocity源码中根本就没这两个参数,加入以后,无论是请求或回应,都会按GBK的编码去传递了。

3.当然,在所有的vm文件和JSP文件里也要加入  pageEncoding="GBK" 。

http://it.chinawin.net/softwaredev/article-16fb6.html

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

这是velocity的官网:http://velocity.apache.org/

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

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

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

项目结构:

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

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

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

==============================================================

代码部分:

==============================================================

/Apache-Velocity-java/src/com/b510/velocity/test/VelocityTest.java

  1 /**
2 *
3 */
4 package com.b510.velocity.test;
5
6 import java.io.StringWriter;
7 import java.text.SimpleDateFormat;
8 import java.util.Date;
9
10 import org.apache.velocity.Template;
11 import org.apache.velocity.VelocityContext;
12 import org.apache.velocity.app.VelocityEngine;
13
14 import com.b510.velocity.bean.Mail;
15 import com.b510.velocity.bean.User;
16
17 /**
18 * 测试类
19 *
20 * @author hongten<br>
21 * @date 2013-3-9
22 */
23 public class VelocityTest {
24
25 public static final String HELLO_WORLD_VM_PATH = "vms/helloWorld.vm";
26 public static final String USER_INFO_VM_PATH = "vms/userInfo.vm";
27 public static final String EMAIL_TEMPLATE_VM_PATH = "vms/emailTemplate.vm";
28
29 public static void main(String[] args) throws Exception {
30 sayHelloFromVM(HELLO_WORLD_VM_PATH);
31 testUser(USER_INFO_VM_PATH);
32 testEmail(EMAIL_TEMPLATE_VM_PATH);
33 }
34
35 /**
36 * 简单的hello world
37 *
38 * @param fileVM
39 * @throws Exception
40 */
41 public static void sayHelloFromVM(String fileVM) throws Exception {
42 VelocityEngine ve = new VelocityEngine();
43 ve.init();
44 Template t = ve.getTemplate(fileVM);
45 VelocityContext context = new VelocityContext();
46 context.put("hello", "Hello world!!");
47 StringWriter writer = new StringWriter();
48 t.merge(context, writer);
49 System.out.println(writer.toString());
50 }
51
52 /**
53 * test User
54 *
55 * @param fileVM
56 * @throws Exception
57 */
58 public static void testUser(String fileVM) throws Exception {
59 VelocityEngine ve = new VelocityEngine();
60 ve.init();
61
62 Template template = ve.getTemplate(fileVM);
63 VelocityContext velocityContext = new VelocityContext();
64 User user = new User();
65 user.setEmail("hongtenzone@foxmail.com");
66 user.setName("hongten");
67 user.setBirthday("1990-11-18");
68 velocityContext.put("user", user);
69 StringWriter stringWriter = new StringWriter();
70 template.merge(velocityContext, stringWriter);
71
72 System.out.println(stringWriter.toString());
73 }
74
75 /**
76 * test email
77 *
78 * @param fileVM
79 * @throws Exception
80 */
81 public static void testEmail(String fileVM) throws Exception {
82 VelocityEngine velocityEngine = new VelocityEngine();
83 velocityEngine.init();
84
85 Template template = velocityEngine.getTemplate(fileVM);
86 VelocityContext velocityContext = new VelocityContext();
87 Mail mail = new Mail();
88 mail.setContent("2013年腾讯开发者新扶持政策解读及创业机会所在");
89 mail.setReceiverMail("hongtenzone@foxmail.com");
90 mail.setReceiverName("Hongten");
91 mail.setSenderMail("opensns_noreply@tencent.com");
92 mail.setSenderName("腾讯开放平台");
93 mail.setSenderWebSite("open.qq.com");
94 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
95 "yyyy-MM-dd HH:mm:ss");
96 mail.setDate(simpleDateFormat.format(new Date()));
97 velocityContext.put("mail", mail);
98 StringWriter stringWriter = new StringWriter();
99 template.merge(velocityContext, stringWriter);
100
101 System.out.println(stringWriter.toString());
102 }
103 }

/Apache-Velocity-java/src/com/b510/velocity/bean/User.java

 1 /**
2 *
3 */
4 package com.b510.velocity.bean;
5
6
7 /**
8 * 用户实体类
9 *
10 * @author hongten<br>
11 * @date 2013-3-9
12 */
13 public class User {
14
15 /**
16 * 用户编号
17 */
18 private Integer id;
19 /**
20 * 用户名称
21 */
22 private String name;
23 /**
24 * 密码
25 */
26 private String password;
27 /**
28 * 生日
29 */
30 private String birthday;
31 /**
32 * 邮箱
33 */
34 private String email;
35
36 public Integer getId() {
37 return id;
38 }
39
40 public void setId(Integer id) {
41 this.id = id;
42 }
43
44 public String getName() {
45 return name;
46 }
47
48 public void setName(String name) {
49 this.name = name;
50 }
51
52 public String getPassword() {
53 return password;
54 }
55
56 public void setPassword(String password) {
57 this.password = password;
58 }
59
60 public String getBirthday() {
61 return birthday;
62 }
63
64 public void setBirthday(String birthday) {
65 this.birthday = birthday;
66 }
67
68 public String getEmail() {
69 return email;
70 }
71
72 public void setEmail(String email) {
73 this.email = email;
74 }
75
76 }

/Apache-Velocity-java/src/com/b510/velocity/bean/Mail.java

  1 /**
2 *
3 */
4 package com.b510.velocity.bean;
5
6 /**
7 * 邮件
8 *
9 * @author hongten<br>
10 * @date 2013-3-9
11 */
12 public class Mail {
13
14 private Integer id;
15 /**
16 * 发件人
17 */
18 private String senderName;
19 /**
20 * 发件人邮箱
21 */
22 private String senderMail;
23 /**
24 * 发件人网址
25 */
26 private String senderWebSite;
27 /**
28 * 收件人
29 */
30 private String receiverName;
31 /**
32 * 收件人邮箱
33 */
34 private String receiverMail;
35 /**
36 * 内容
37 */
38 private String content;
39 /**
40 * 日期
41 */
42 private String date;
43
44 public Integer getId() {
45 return id;
46 }
47
48 public void setId(Integer id) {
49 this.id = id;
50 }
51
52 public String getSenderName() {
53 return senderName;
54 }
55
56 public void setSenderName(String senderName) {
57 this.senderName = senderName;
58 }
59
60 public String getSenderMail() {
61 return senderMail;
62 }
63
64 public void setSenderMail(String senderMail) {
65 this.senderMail = senderMail;
66 }
67
68 public String getReceiverName() {
69 return receiverName;
70 }
71
72 public void setReceiverName(String receiverName) {
73 this.receiverName = receiverName;
74 }
75
76 public String getReceiverMail() {
77 return receiverMail;
78 }
79
80 public void setReceiverMail(String receiverMail) {
81 this.receiverMail = receiverMail;
82 }
83
84 public String getContent() {
85 return content;
86 }
87
88 public void setContent(String content) {
89 this.content = content;
90 }
91
92 public String getDate() {
93 return date;
94 }
95
96 public void setDate(String date) {
97 this.date = date;
98 }
99
100 public String getSenderWebSite() {
101 return senderWebSite;
102 }
103
104 public void setSenderWebSite(String senderWebSite) {
105 this.senderWebSite = senderWebSite;
106 }
107
108 }

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

1 ##test hello world!
2
3 $hello

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

 1 ##测试User
2
3 A: what's your name?
4 B: $user.name
5
6 A: what's your birthday?
7 B: $user.birthday
8
9 A: what's your email address?
10 B: $user.email
11
12 A: good!

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

 1 ##测试 email
2
3 $mail.senderName message notification
4 Sender : $mail.senderName<$mail.senderMail>
5 Date : $mail.date
6 Receiver : $mail.receiverName<$mail.receiverMail>
7
8 Dear $mail.receiverMail:
9 $mail.senderName send a message notification as following:
10
11 $mail.content
12
13 please quick login the $mail.senderWebSite message center and have a look.
14
15 $mail.senderName Team
16

因为velocity源码中默认的编码为:

1 # ----------------------------------------------------------------------------
2 # T E M P L A T E E N C O D I N G
3 # ----------------------------------------------------------------------------
4
5 input.encoding=ISO-8859-1
6 output.encoding=ISO-8859-1

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

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

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

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

apache的开源项目-模板引擎(Velocity)(转)的更多相关文章

  1. apache基金会开源项目简介

    apache基金会开源项目简介   项目名称 描述 HTTP Server 互联网上首屈一指的HTTP服务器 Abdera Apache  Abdera项目的目标是建立一个功能完备,高效能的IETF ...

  2. httl开源JAVA模板引擎,动态HTML页面输出

    HTTL(Hyper-Text Template Language)是一个适用于HTML输出的开源JAVA模板引擎,适用于动态HTML页面输出,可用于替代JSP页面,它的指令类似于Velocity. ...

  3. 模板引擎 Velocity

    模板引擎 Velocity 一.Velocity简介: Velocity是一个基于java的模板引擎(template engine).它允许任何人仅仅简单的使用模板语言(template langu ...

  4. [Java] 模板引擎 Velocity 随笔

    Velocity 是一个基于 Java 的模板引擎. 本博文演示 Velocity 的 HelloWord 以及分支条件. HelloWord.vm,模板文件. templateDemo.java, ...

  5. web基础----->模板引擎Velocity的使用(一)

    Velocity 是一个基于 Java 的模板引擎框架,提供的模板语言可以使用在 Java 中定义的对象和变量上.今天我们就学习一下Velocity的用法. Velocity的第一个例子 项目的主体是 ...

  6. 基于.NET的免费开源的模板引擎---VTemplate(转)

    1.VTemplate模板引擎的简介 VTemplate模板引擎也简称为VT,是基于.NET的模板引擎,它允许任何人使用简单的类似HTML语法的模板语言来引用.NET里定义的对象.当VTemplate ...

  7. OSCHina技术导向:Java模板引擎velocity

    OSChina 采用 velocity 作为页面模板 Velocity是一个基于java的模板引擎(template engine).它允许任何人仅仅简单的使用模板语言(template langua ...

  8. 如何从零开始参与 Apache 顶级开源项目?| 墙裂推荐

    ​ 写在开头 从 2021 开始,有一个很有意思的说法经常在各大技术媒体或开源论坛中出现,「开源正在吞噬一切」.不论是否言过其实,从一个行业从业者的切身感知来看,开源确实从少数极客的小众文化成为主流的 ...

  9. 模板引擎Velocity学习系列-#set指令

    #set指令 #set指令用于向一个变量或者对象赋值. 格式: #set($var = value) LHS是一个变量,不要使用特殊字符例如英文句号等,不能用大括号括起来.测试发现#set($user ...

随机推荐

  1. 解决项目打包过程检出项目出现 svn:e15500错误

    svn:E15500 is already a working copy for a different url 原因:文件夹含有svn信息的隐藏文件未删除 解决办法:把该文件夹删除掉,然后重新建立同 ...

  2. sqlplus

    以超级管理员登录 sqlplus sys/123 as sysdba 解锁用户 alter user xutianhao account unlock

  3. 使用contentprovider实现的日记(转)

    目录结构: MyDiaryActivity.java package com.zhang.myDiary; import com.zhang.myDiary.DiaryColumn.DiaryClmn ...

  4. Eclipse生成Jar包方法

    Eclipse生成jar包   第一:普通类导出jar包,我说的普通类就是指此类包含main方法,并且没有用到别的jar包. 1.在eclipse中选择你要导出的类或者package,右击,选择Exp ...

  5. 模拟QQ系统设置面板实现功能

    业务需求: 基于网盘客户端的实现,原有网盘的设置面板无论从界面显示还是从业务需求都不能满足我们的正常需求.当前的要求是,模拟QQ系统设置的面板实现当前我们网盘中的基本配置功能.在完成这篇文章时已将基本 ...

  6. 用来解析,格式化,存储和验证国际电话号码:libphonenumber

    用来解析,格式化,存储和验证国际电话号码:libphonenumber libphonenumber是Google的公共Java.C++和Javascript库用来解析,格式化,存储和验证国际电话号码 ...

  7. WCF技术剖析之二十二: 深入剖析WCF底层异常处理框架实现原理[中篇]

    原文:WCF技术剖析之二十二: 深入剖析WCF底层异常处理框架实现原理[中篇] 在[上篇]中,我们分别站在消息交换和编程的角度介绍了SOAP Fault和FaultException异常.在服务执行过 ...

  8. 十天学习PHP之第四天

    学习目的:学会连接数据库  PHP简直就是一个函数库,丰富的函数使PHP的某些地方相当简单.建议大家down一本PHP的函数手冊,总用得到. 我这里就简单说一下连接MYSQL数据库.  1.mysql ...

  9. ARMv8 Linux内核源代码分析:__flush_dcache_all()

    1.1 /* *  __flush_dcache_all() *  Flush the wholeD-cache. * Corrupted registers: x0-x7, x9-x11 */ EN ...

  10. FMXUI - UI.Dialog 示例

    在 FMXUI 开源库,增加了 UI.Dialog 单元.此单元实现了跨平台的基础对话框组件.使用时引用 UI.Dialog 即可.如果需要自定义对话框的样式, 可以添加一个 TDialogStyle ...