﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>BlogJava-Java Stop Here-文章分类-Velocity</title><link>http://www.blogjava.net/faithwind/category/8323.html</link><description>Love Java ,because you are my first lady !^_^</description><language>zh-cn</language><lastBuildDate>Fri, 02 Mar 2007 00:35:37 GMT</lastBuildDate><pubDate>Fri, 02 Mar 2007 00:35:37 GMT</pubDate><ttl>60</ttl><item><title>Velocity简介</title><link>http://www.blogjava.net/faithwind/articles/35091.html</link><dc:creator>黑咖啡</dc:creator><author>黑咖啡</author><pubDate>Mon, 13 Mar 2006 09:30:00 GMT</pubDate><guid>http://www.blogjava.net/faithwind/articles/35091.html</guid><wfw:comment>http://www.blogjava.net/faithwind/comments/35091.html</wfw:comment><comments>http://www.blogjava.net/faithwind/articles/35091.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/faithwind/comments/commentRss/35091.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/faithwind/services/trackbacks/35091.html</trackback:ping><description><![CDATA[<TABLE cellSpacing=0 cellPadding=0 width="100%" border=0>
<TBODY>
<TR>
<TD vAlign=top width="86%">1.Velocity 的使用<BR>Velocity是一个开放源吗的模版引擎，由apache.org小组负责开发，现在最新的版本是Velocity1.3.1，http://jakarta.apache.org/velocity/index.html 可以了解Velocity的最新信息。<BR>Velocity允许我们在模版中设定变量，然后在运行时，动态的将数据插入到模版中，替换这些变量。<BR>例如：<BR>&lt;html&gt;<BR>&lt;body&gt;HELLO $CUSTOMERNAME&lt;/body&gt;<BR>&lt;/html&gt;<BR>我们可以在运行时得到客户的名字，然后把它插入到这个模版中替换变量$CUSTOMERNAME，整个替换过程是由Velocity进行控制的，而且java的调用代码也非常简单，如我们可以在java代码中这样调用<BR>/***********************************************************/<BR>//这个文件中设定了Velocity使用的log4j的配置和Velocity的模版文件所在的目录<BR>Velocity.init("D:\\Template\\resource\\jt.properties"); <BR>//模版文件名，模版文件所在的路径在上一条语句中已经设置了<BR>Template template = Velocity.getTemplate("hello.vm", "gb2312"); <BR>//实例化一个Context <BR>VelocityContext context = new VelocityContext();<BR>//把模版变量的值设置到context中 <BR>context.put("CUSTOMERNAME", "My First Template Engine ---- Velocity.");<BR>//开始模版的替换<BR>template.merge(context, writer);<BR>//写到文件中<BR>PrintWriter filewriter = new PrintWriter(new FileOutputStream(outpath),true);<BR>filewriter.println(writer.toString());<BR>filewriter.close();<BR>/***********************************************************/<BR><BR>这就是整个java的代码，非常的简单。如果我们有多个模版变量，我们仅需要把这些模版变量的值设置到context中。<BR>下面我们简单的分析一下，Velocity引擎读取模板文件时，它直接输出文件中所有的文本，但以$字符开头的除外，$符号标识着一个模版变量位置，<BR>context.put("CUSTOMERNAME", "My First Template Engine ---- Velocity.");<BR>当 Velocity 模板引擎解析并输出模板的结果时，模板中所有出现$CUSTOMERNAME的地方都将插入客户的名字，即被加入到VelocityContext的对象的toString()方法返回值将替代Velocity变量（模板中以$开头的变量）。<BR>模板引擎中最强大、使用最频繁的功能之一是它通过内建的映像（Reflection）引擎查找对象信息的能力。这个映像引擎允许用一种方便的Java“.”类似的操作符，提取任意加入到VelocityContext的对象的任何公用方法的值，或对象的任意数据成员。<BR>映像引擎还带来了另外一个改进：快速引用JavaBean的属性。使用JavaBean属性的时候，我们可以忽略get方法和括号。请看下面这个模板的例子。<BR>&lt;html&gt;<BR>&lt;body&gt;<BR>Name:$Customer.Name()<BR>Address:$Customer.Address()<BR>Age:$Customer.Age()<BR>&lt;/body&gt;<BR>&lt;/html&gt;<BR><BR>java的代码： <BR>/***********************************************************/<BR>//设置客户信息<BR>Customer mycustomer = new Customer();<BR>mycustomer.setName("Velocity");<BR>mycustomer.setAddress("jakarta.apache.org/velocity/index.html");<BR>mycustomer.setAge(2);<BR>//这个文件中设定了 Velocity 使用的 Log4j 的配置和Velocity的模版文件所在的目录Velocity.init("D:\\Template\\resource\\jt.properties");<BR>//模版文件名，模版文件所在的路径在上一条语句中已经设置了<BR>Template template = Velocity.getTemplate("hello.vm", "gb2312");<BR>//实例化一个Context<BR>VelocityContext context = new VelocityContext();<BR>//把模版变量的值设置到context中<BR>context.put("Customer", mycustomer);<BR>//开始模版的替换<BR>template.merge(context, writer);<BR>//写到文件中<BR>PrintWriter filewriter = new PrintWriter(new FileOutputStream(outpath),true);<BR>filewriter.println(writer.toString());<BR>filewriter.close();<BR>输出结果：<BR>&lt;html&gt;<BR>&lt;body&gt;<BR>Name:Velocity<BR>Address:jakarta.apache.org/velocity/index.html<BR>Age:2<BR>&lt;/body&gt;<BR>&lt;/html&gt;<BR>除了替换变量之外，象Velocity高级引擎还能做其他许多事情，它们有用来比较和迭代的内建指令，通过这些指令我们可以完成程序语言中的条件判断语句和循环语句等。<BR>例如，我们想要输出年龄等于2的所有客户的信息，我们可以这样定义我们的模版<BR>模版：<BR>&lt;html&gt;<BR>&lt;body&gt;<BR>&lt;table&gt;<BR>&lt;tr&gt;<BR>&lt;td&gt;名称&lt;/td&gt;<BR>&lt;td&gt;地址&lt;/td&gt;<BR>&lt;td&gt;年龄&lt;/td&gt;<BR>&lt;/tr&gt;<BR>#foreach ($Customer in $allCustomer)<BR>#if($Customer.Age()=="2")<BR>&lt;tr&gt;<BR>&lt;td&gt;$Customer.Name()&lt;/td&gt;<BR>&lt;td&gt;$Customer.Address()&lt;/td&gt;<BR>&lt;td&gt;$Customer.Age()&lt;/td&gt;<BR>&lt;/tr&gt;<BR>#end<BR>#end<BR>&lt;/table&gt;<BR>&lt;/body&gt;<BR>&lt;/html&gt;<BR><BR>java的代码： <BR>/******************************************************/<BR>//设置客户信息<BR>ArrayList allMyCustomer = new ArrayList();<BR>//客户1<BR>Customer mycustomer1 = new Customer();<BR>mycustomer1.setName("Velocity");<BR>mycustomer1.setAddress("jakarta.apache.org/velocity/index.html");<BR>mycustomer1.setAge(2);<BR>//客户2<BR>Customer mycustomer2 = new Customer();<BR>mycustomer2.setName("Tomcat");<BR>mycustomer2.setAddress("jakarta.apache.org/tomcat/index.html");<BR>mycustomer2.setAge(3);<BR>//客户3<BR>Customer mycustomer3 = new Customer();<BR>mycustomer3.setName("Log4J");<BR>mycustomer3.setAddress("jakarta.apache.org/log4j/docs/index.html");<BR>mycustomer3.setAge(2);<BR>//添加到allMyCustomer(ArrayList)中.<BR>allMyCustomer.add(mycustomer1);<BR>allMyCustomer.add(mycustomer2);<BR>allMyCustomer.add(mycustomer3);<BR>//这个文件中设定了Velocity使用的log4j的配置和Velocity的模版文件所在的目<BR>Velocity.init("D:\\Template\\resource\\jt.properties");<BR>//模版文件名，模版文件所在的路径在上一条语句中已经设置了<BR>Template template =Velocity.getTemplate("hello.vm", "gb2312");<BR>//实例化一个Context<BR>VelocityContext context = new VelocityContext();<BR>/** 注意这里我们仅仅需要给一个模版变量负值 */<BR>context.put("allCustomer", allMyCustomer);<BR>//开始模版的替换<BR>template.merge(context, writer);<BR>//写到文件中<BR>PrintWriter filewriter = new PrintWriter(new FileOutputStream(outpath),true);<BR>filewriter.println(writer.toString());<BR>filewriter.close();<BR>/******************************************************/<BR>结果：<BR>&lt;html&gt;<BR>&lt;body&gt;<BR>&lt;table&gt;<BR>&lt;tr&gt;<BR>&lt;td&gt;名称&lt;/td&gt;<BR>&lt;td&gt;地址&lt;/td&gt;<BR>&lt;td&gt;年龄&lt;/td&gt;<BR>&lt;/tr&gt;<BR>&lt;tr&gt;<BR>&lt;td&gt;Velocity&lt;/td&gt;<BR>&lt;td&gt;jakarta.apache.org/velocity/index.html&lt;/td&gt;<BR>&lt;td&gt;2&lt;/td&gt;<BR>&lt;/tr&gt;<BR>&lt;tr&gt;<BR>&lt;td&gt;Log4J&lt;/td&gt;<BR>&lt;td&gt;jakarta.apache.org/log4j/docs/index.html&lt;/td&gt;<BR>&lt;td&gt;2&lt;/td&gt;<BR>&lt;/tr&gt;<BR>&lt;/table&gt;<BR>&lt;/body&gt;<BR>&lt;/html&gt;<BR><BR>#if 语句完成逻辑判断，这个我想不用多说了。<BR>allCustomer对象包含零个或者多个Customer对象。由于ArrayList (List, HashMap, HashTable, Iterator, Vector等)属于Java Collections Framework的一部分，我们可以用#foreach指令迭代其内容。我们不用担心如何定型对象的类型——映像引擎会为我们完成这个任务。#foreach指令的一般格式是“#foreach in ”。#foreach指令迭代list，把list中的每个元素放入item参数，然后解析#foreach块内的内容。对于list内的每个元素，#foreach块的内容都会重复解析一次。从效果上看，它相当于告诉模板引擎说：“把list中的每一个元素依次放入item变量，每次放入一个元素，输出一次#foreach块的内容”。<BR><BR>2.MVC设计模型<BR><BR>使用模板引擎最大的好处在于，它分离了代码（或程序逻辑）和表现（输出）。由于这种分离，你可以修改程序逻辑而不必担心邮件消息本身；类似地，你（或公关部门的职员）可以在不重新编译程序的情况下，重新编写客户列表。实际上，我们分离了系统的数据模式（Data Model，即提供数据的类）、控制器（Controller，即客户列表程序）以及视图（View，即模板）。这种三层体系称为Model-View-Controller模型（MVC）。<BR>如果遵从MVC模型，代码分成三个截然不同的层，简化了软件开发过程中所有相关人员的工作。 <BR>结合模板引擎使用的数据模式可以是任何Java对象，最好是使用Java Collection Framework的对象。控制器只要了解模板的环境（如VelocityContext），一般这种环境都很容易使用。<BR>一些关系数据库的“对象-关系”映射工具能够和模板引擎很好地协同，简化JDBC操作；对于EJB，情形也类似。 模板引擎与MVC中视图这一部分的关系更为密切。模板语言的功能很丰富、强大，足以处理所有必需的视图功能，同时它往往很简单，不熟悉编程的人也可以使用它。模板语言不仅使得设计者从过于复杂的编程环境中解脱出来，而且它保护了系统，避免了有意或无意带来危险的代码。例如，模板的编写者不可能编写出导致无限循环的代码，或侵占大量内存的代码。不要轻估这些安全机制的价值；大多数模板编写者不懂得编程，从长远来看，避免他们接触复杂的编程环境相当于节省了你自己的时间。 许多模板引擎的用户相信，在采用模板引擎的方案中，控制器部分和视图部分的明确分离，再加上模板引擎固有的安全机制，使得模板引擎足以成为其他内容发布系统（比如JSP）的替代方案。因此，Java模板引擎最常见的用途是替代JSP也就不足为奇了。 <BR><BR>3.HTML处理<BR><BR>由于人们总是看重模板引擎用来替换JSP的作用，有时他们会忘记模板还有更广泛的用途。到目前为止，模板引擎最常见的用途是处理HTML Web内容。但我还用模板引擎生成过SQL、email、XML甚至Java源代码。<BR></TD>
<TD vAlign=top width="14%">
<DIV align=right><FONT color=gray>&nbsp;&nbsp;&nbsp;&nbsp;</FONT></DIV></TD></TR></TBODY></TABLE><img src ="http://www.blogjava.net/faithwind/aggbug/35091.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/faithwind/" target="_blank">黑咖啡</a> 2006-03-13 17:30 <a href="http://www.blogjava.net/faithwind/articles/35091.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>一篇Velocity入门文章</title><link>http://www.blogjava.net/faithwind/articles/34990.html</link><dc:creator>黑咖啡</dc:creator><author>黑咖啡</author><pubDate>Mon, 13 Mar 2006 02:44:00 GMT</pubDate><guid>http://www.blogjava.net/faithwind/articles/34990.html</guid><wfw:comment>http://www.blogjava.net/faithwind/comments/34990.html</wfw:comment><comments>http://www.blogjava.net/faithwind/articles/34990.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/faithwind/comments/commentRss/34990.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/faithwind/services/trackbacks/34990.html</trackback:ping><description><![CDATA[这是一篇Velocity入门级的文章，虽然很简单，但确实能够说明Velocity的工作原理，值得一读。<BR><BR><STRONG>使用Velocity 模板引擎开发网站</STRONG><BR><BR>Velocity 是如何工作的呢？ 虽然大多 Velocity 的应用都是基于 Servlet 的网页制作。但是为了说明 Velocity 的使用，我决定采用更通用的 Java application 来说明它的工作原理。 <BR>　　似乎所有语言教学的开头都是采用 HelloWorld 来作为第一个程序的示例。这里也不例外。 <BR><BR>　　任何 Velocity 的应用都包括两个方面:<BR>　　第一是： 模板制作，在我们这个例子中就是 hellosite.vm:<BR>　　它的内容如下（虽然不是以 HTML 为主，但是这很容易改成一个 html 的页面）<BR><BR>Hello $name! Welcome to $site world!<BR>　　第二是 Java 程序部分：<BR>　　下面是 Java 代码<BR>
<DIV class=UBBPanel>
<DIV class=UBBTitle><IMG style="MARGIN: 0px 2px -3px 0px" alt=程序代码 src="http://www.junesky.org/blog/images/code.gif"> 程序代码</DIV>
<DIV class=UBBContent>import <A href="http://www.sun.com/" target=_blank>java</A>.io.StringWriter;<BR>import org.apache.velocity.app.VelocityEngine;<BR>import org.apache.velocity.Template;<BR>import org.apache.velocity.VelocityContext;<BR>public class HelloWorld{<BR>&nbsp;public static void main( String[] args )throws Exception{<BR>&nbsp;&nbsp;/* first, get and initialize an engine */<BR>&nbsp;&nbsp;VelocityEngine ve = new VelocityEngine();<BR>&nbsp;&nbsp;ve.init();<BR>&nbsp;&nbsp;/* next, get the Template */<BR>&nbsp;&nbsp;Template t = ve.getTemplate( "hellosite.vm" );<BR>&nbsp;&nbsp;/* create a context and add data */<BR>&nbsp;&nbsp;VelocityContext context = new VelocityContext();<BR>&nbsp;&nbsp;context.put("name", "Eiffel Qiu");<BR>&nbsp;&nbsp;context.put("site", "<A href="http://www.eiffelqiu.com/" target=_blank>http://www.eiffelqiu.com</A>");<BR>&nbsp;&nbsp;/* now render the template into a StringWriter */<BR>&nbsp;&nbsp;StringWriter writer = new StringWriter();<BR>&nbsp;&nbsp;t.merge( context, writer );<BR>&nbsp;&nbsp;/* show the World */<BR>&nbsp;&nbsp;System.out.println( writer.toString() ); <BR>&nbsp;}<BR>}</DIV></DIV><BR>将两个文件放在同一个目录下，编译运行，结果是： <BR>Hello Eiffel Qiu! Welcome to <A href="http://www.eiffelqiu.com/" target=_blank>http://www.eiffelqiu.com</A> world <BR><BR>　　为了保证运行顺利，请从 Velocity 的网站 <A href="http://jakarta.apache.org/velocity/" target=_blank>http://jakarta.apache.org/velocity/</A> 上下载 Velocity 的运行包，将其中的 Velocity Jar 包的路径放在系统的 Classpath 中，这样就可以编译和运行以上的程序了。<BR><BR>这个程序很简单，但是它能让你清楚的了解 Velocity 的基本工作原理。程序中其他部分基本上很固定，最主要的部分在以下代码 <BR><BR>　　这里 Velocity 获取模板文件，得到模板引用<BR><BR>
<DIV class=UBBPanel>
<DIV class=UBBTitle><IMG style="MARGIN: 0px 2px -3px 0px" alt=程序代码 src="http://www.junesky.org/blog/images/code.gif"> 程序代码</DIV>
<DIV class=UBBContent>/* next, get the Template */<BR>Template t = ve.getTemplate( "hellosite.vm" );</DIV></DIV><BR>　　这里，初始化环境，并将数据放入环境<BR><BR>
<DIV class=UBBPanel>
<DIV class=UBBTitle><IMG style="MARGIN: 0px 2px -3px 0px" alt=程序代码 src="http://www.junesky.org/blog/images/code.gif"> 程序代码</DIV>
<DIV class=UBBContent>/* create a context and add data */<BR>VelocityContext context = new VelocityContext();<BR>context.put("name", "Eiffel Qiu");<BR>context.put("site", "<A href="http://www.eiffelqiu.com/" target=_blank>http://www.eiffelqiu.com</A>");</DIV></DIV><BR>　　其他代码比较固定，但是也非常重要，但是对于每个应用来说写法都很相同：<BR>这是初始化 Velocity 模板引擎<BR><BR>
<DIV class=UBBPanel>
<DIV class=UBBTitle><IMG style="MARGIN: 0px 2px -3px 0px" alt=程序代码 src="http://www.junesky.org/blog/images/code.gif"> 程序代码</DIV>
<DIV class=UBBContent>/* first, get and initialize an engine */<BR>VelocityEngine ve = new VelocityEngine();<BR>ve.init();</DIV></DIV><BR>　　这是用来将环境变量和输出部分结合。<BR><BR>
<DIV class=UBBPanel>
<DIV class=UBBTitle><IMG style="MARGIN: 0px 2px -3px 0px" alt=程序代码 src="http://www.junesky.org/blog/images/code.gif"> 程序代码</DIV>
<DIV class=UBBContent>StringWriter writer = new StringWriter();<BR>t.merge( context, writer );<BR>/* show the World */<BR>System.out.println( writer.toString() ); </DIV></DIV><BR>　　记住，这在将来的 servlet 应用中会有所区别，因为网页输出并不和命令行输出相同，如果用于网页输出，将并不通过 System.out 输出。这会在以后的教程中给大家解释的。 <BR><BR>那让我来总结一下 Velocity 真正的工作原理： <BR>　　Velocity 解决了如何在 Servlet 和 网页之间传递数据的问题，当然这种传输数据的机制是在 MVC 模式上进行的，也就是View 和 Modle , Controller 之间相互独立工作，一方的修改不影响其他方变动，他们之间是通过环境变量（Context）来实现的，当然双方网页制作一方和后台程序一方要相互约定好对所传递变量的命名约定，比如上个程序例子中的 site, name 变量，它们在网页上就是 $name ,$site 。 这样只要双方约定好了变量名字，那么双方就可以独立工作了。 无论页面如何变化，只要变量名不变，那么后台程序就无需改动，前台网页也可以任意由网页制作人员修改。这就是 Velocity 的工作原理。 <BR><BR>　　你会发现简单变量名通常无法满足网页制作显示数据的需要，比如我们经常会循环显示一些数据集，或者是根据一些数据的值来决定如何显示下一步的数据， Velocity 同样提供了循环，判断的简单语法以满足网页制作的需要。Velocity 提供了一个简单的模板语言以供前端网页制作人员使用，这个模板语言足够简单（大部分懂得 <A href="http://www.sun.com/" target=_blank>java</A>script 的人就可以很快掌握，其实它比 <A href="http://www.sun.com/" target=_blank>java</A>script 要简单的多），当然这种简单是刻意的，因为它不需要它什么都能做， View 层其实不应该包含更多的逻辑，Velocity 的简单模板语法可以满足你所有对页面显示逻辑的需要，这通常已经足够了，这里不会发生象 jsp 那样因为一个无限循环语句而毁掉系统的情况，jsp 能做很多事情，Sun 在制定 Jsp 1.0 标准的时候，没有及时的限定程序员在 jsp 插入代码逻辑，使得早期的jsp 代码更象是 php 代码，它虽然强大，但是对显示层逻辑来说，并不必要，而且会使 MVC 三层的逻辑结构发生混淆。<img src ="http://www.blogjava.net/faithwind/aggbug/34990.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/faithwind/" target="_blank">黑咖啡</a> 2006-03-13 10:44 <a href="http://www.blogjava.net/faithwind/articles/34990.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>spring+velocity自动发送邮件</title><link>http://www.blogjava.net/faithwind/articles/34987.html</link><dc:creator>黑咖啡</dc:creator><author>黑咖啡</author><pubDate>Mon, 13 Mar 2006 02:35:00 GMT</pubDate><guid>http://www.blogjava.net/faithwind/articles/34987.html</guid><wfw:comment>http://www.blogjava.net/faithwind/comments/34987.html</wfw:comment><comments>http://www.blogjava.net/faithwind/articles/34987.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/faithwind/comments/commentRss/34987.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/faithwind/services/trackbacks/34987.html</trackback:ping><description><![CDATA[<SPAN class=content>1.下载spring及velocity类库，<BR><BR>email配置文件：mail.properties：<BR>mail.default.from=jfishsz@163.com<BR>mail.host=smtp.163.com<BR>mail.username=xxxxxx<BR>mail.password=xxxxxx<BR>mail.smtp.auth=true<BR>mail.smtp.timeout=25000<BR><BR>spring配置文件：applicationContext.xml<BR>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<BR>&lt;!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"<BR>"<A href="http://www.springframework.org/dtd/spring-beans.dtd" target=_blank><FONT color=#000000>http://www.springframework.org/dtd/spring-beans.dtd</FONT></A>"&gt;<BR><BR>&lt;beans&gt;<BR>&nbsp; &lt;!-- For mail settings and future properties files --&gt;<BR>&nbsp; &lt;bean id="propertyConfigurer"<BR>&nbsp; &nbsp; class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt;<BR>&nbsp; &nbsp; &lt;property name="locations"&gt;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &lt;list&gt;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;value&gt;classpath:mail.properties&lt;/value&gt;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &lt;/list&gt;<BR>&nbsp; &nbsp; &lt;/property&gt;<BR>&nbsp; &lt;/bean&gt;<BR>&nbsp; &lt;bean id="mailSender"<BR>&nbsp; &nbsp; class="org.springframework.mail.javamail.JavaMailSenderImpl"&gt;<BR>&nbsp; &nbsp; &lt;property name="host"&gt;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &lt;value&gt;${mail.host}&lt;/value&gt;<BR>&nbsp; &nbsp; &lt;/property&gt;<BR>&nbsp; &nbsp; &lt;property name="username"&gt;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &lt;value&gt;${mail.username}&lt;/value&gt;<BR>&nbsp; &nbsp; &lt;/property&gt;<BR>&nbsp; &nbsp; &lt;property name="password"&gt;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &lt;value&gt;${mail.password}&lt;/value&gt;<BR>&nbsp; &nbsp; &lt;/property&gt;<BR>&nbsp; &nbsp; &lt;property name="javaMailProperties"&gt;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &lt;props&gt;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;prop key="mail.smtp.auth"&gt;${mail.smtp.auth}&lt;/prop&gt;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;prop key="mail.smtp.timeout"&gt;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ${mail.smtp.timeout}<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;/prop&gt;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &lt;/props&gt;<BR>&nbsp; &nbsp; &lt;/property&gt;<BR>&nbsp; &lt;/bean&gt;<BR>&nbsp; &lt;bean id="mailMessage"<BR>&nbsp; &nbsp; class="org.springframework.mail.SimpleMailMessage"<BR>&nbsp; &nbsp; singleton="false"&gt;<BR>&nbsp; &nbsp; &lt;property name="from"&gt;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &lt;value&gt;${mail.default.from}&lt;/value&gt;<BR>&nbsp; &nbsp; &lt;/property&gt;<BR>&nbsp; &nbsp; <BR>&nbsp; &lt;/bean&gt;<BR>&nbsp; &lt;bean id="sendMail" class="net.pms.email.SendMail"&gt;<BR>&nbsp; &nbsp; &lt;property name="mailSender" ref="mailSender" /&gt;<BR>&nbsp; &nbsp; &lt;property name="message" ref="mailMessage" /&gt;<BR>&nbsp; &nbsp; &lt;property name="velocityEngine" ref="velocityEngine" /&gt;<BR>&nbsp; &lt;/bean&gt;<BR>&nbsp; &lt;!-- Configure Velocity for sending e-mail --&gt;<BR>&nbsp; &lt;bean id="velocityEngine"<BR>&nbsp; &nbsp; class="org.springframework.ui.velocity.VelocityEngineFactoryBean"&gt;<BR>&nbsp; &nbsp; &lt;property name="velocityProperties"&gt;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &lt;props&gt;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;prop key="resource.loader"&gt;class&lt;/prop&gt;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;prop key="class.resource.loader.class"&gt;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;/prop&gt;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &lt;prop key="velocimacro.library"&gt;&lt;/prop&gt;<BR>&nbsp; &nbsp; &nbsp; &nbsp; &lt;/props&gt;<BR>&nbsp; &nbsp; &lt;/property&gt;<BR>&nbsp; &lt;/bean&gt;<BR>&lt;/beans&gt;<BR>velocity模板文件：accountCreated.vm：<BR>${message}<BR><BR>Username: ${username}<BR>Password: ${Password}<BR><BR>Login at: ${applicationURL}<BR><BR>2.实现类<BR>SendMail.java<BR>package net.pms.email;<BR><BR>import java.util.Map;<BR><BR>import org.apache.commons.logging.Log;<BR>import org.apache.commons.logging.LogFactory;<BR>import org.apache.velocity.app.VelocityEngine;<BR>import org.apache.velocity.exception.VelocityException;<BR>import org.springframework.mail.MailSender;<BR>import org.springframework.mail.SimpleMailMessage;<BR>import org.springframework.ui.velocity.VelocityEngineUtils;<BR><BR>public class SendMail {<BR>&nbsp; protected static final Log log = LogFactory.getLog(SendMail.class);<BR><BR>&nbsp; private MailSender mailSender;<BR><BR>&nbsp; private SimpleMailMessage message;<BR><BR>&nbsp; private VelocityEngine velocityEngine;<BR><BR>&nbsp; public void setVelocityEngine(VelocityEngine velocityEngine) {<BR>&nbsp; &nbsp; this.velocityEngine = velocityEngine;<BR>&nbsp; }<BR><BR>&nbsp; public void setMailSender(MailSender mailSender) {<BR>&nbsp; &nbsp; this.mailSender = mailSender;<BR>&nbsp; }<BR><BR>&nbsp; public void setMessage(SimpleMailMessage message) {<BR>&nbsp; &nbsp; this.message = message;<BR>&nbsp; }<BR><BR>&nbsp; public void sendEmail(Map model) {<BR>&nbsp; &nbsp; message.setTo("<A href="mailto:jfishsz@163.com"><FONT color=#000000>jfishsz@163.com</FONT></A>");<BR>&nbsp; &nbsp; message.setSubject("subject");<BR>&nbsp; &nbsp; String result = null;<BR>&nbsp; &nbsp; try {<BR>&nbsp; &nbsp; &nbsp; &nbsp; result = VelocityEngineUtils.mergeTemplateIntoString(<BR>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; velocityEngine, "accountCreated.vm", model);<BR>&nbsp; &nbsp; } catch (VelocityException e) {<BR>&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();<BR>&nbsp; &nbsp; }<BR>&nbsp; &nbsp; message.setText(result);<BR>&nbsp; &nbsp; mailSender.send(message);<BR>&nbsp; }<BR>}<BR>测试类：SendMailTest.java<BR>package net.pms.email;<BR><BR>import java.util.HashMap;<BR>import java.util.Map;<BR><BR>import junit.framework.TestCase;<BR><BR>import org.springframework.context.ApplicationContext;<BR>import org.springframework.context.support.ClassPathXmlApplicationContext;<BR><BR>public class SendMailTest extends TestCase {<BR>&nbsp; String[] paths = { "config/applicationContext*.xml" };<BR><BR>&nbsp; ApplicationContext ctx = new ClassPathXmlApplicationContext(paths);<BR><BR>&nbsp; SendMail s = (SendMail) ctx.getBean("sendMail");<BR><BR>&nbsp; protected void setUp() throws Exception {<BR>&nbsp; &nbsp; super.setUp();<BR>&nbsp; }<BR><BR>&nbsp; protected void tearDown() throws Exception {<BR>&nbsp; &nbsp; super.tearDown();<BR>&nbsp; }<BR><BR>&nbsp; /*<BR>&nbsp; * Test method for 'net.pms.email.SendMail.sendEmail(Map)'<BR>&nbsp; */<BR>&nbsp; public void testSendEmail() {<BR>&nbsp; &nbsp; Map model = new HashMap();<BR>&nbsp; &nbsp; model.put("message", "msg");<BR>&nbsp; &nbsp; model.put("username", "jack");<BR>&nbsp; &nbsp; model.put("Password", "666666");<BR>&nbsp; &nbsp; model.put("applicationURL", "<A href="http://www.163.com/" target=_blank><FONT color=#000000>www.163.com</FONT></A>");<BR>&nbsp; &nbsp; s.sendEmail(model);<BR>&nbsp; }<BR><BR>}<BR></SPAN><img src ="http://www.blogjava.net/faithwind/aggbug/34987.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/faithwind/" target="_blank">黑咖啡</a> 2006-03-13 10:35 <a href="http://www.blogjava.net/faithwind/articles/34987.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Velocity的中文指南</title><link>http://www.blogjava.net/faithwind/articles/34669.html</link><dc:creator>黑咖啡</dc:creator><author>黑咖啡</author><pubDate>Fri, 10 Mar 2006 06:56:00 GMT</pubDate><guid>http://www.blogjava.net/faithwind/articles/34669.html</guid><wfw:comment>http://www.blogjava.net/faithwind/comments/34669.html</wfw:comment><comments>http://www.blogjava.net/faithwind/articles/34669.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/faithwind/comments/commentRss/34669.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/faithwind/services/trackbacks/34669.html</trackback:ping><description><![CDATA[&nbsp;&nbsp;&nbsp;&nbsp; 摘要: [文章导读]Velocity 用户指南旨在帮助页面设计者和内容提供者了解Velocity 和其简单而又强大的脚本语言（Velocity Template Language (VTL)）。本指南中有很多示例展示了用Velocity来讲动态内容嵌入到网站之中，但是所有的VTL examples 都同演示用于所有的页面和模版。...&nbsp;&nbsp;<a href='http://www.blogjava.net/faithwind/articles/34669.html'>阅读全文</a><img src ="http://www.blogjava.net/faithwind/aggbug/34669.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/faithwind/" target="_blank">黑咖啡</a> 2006-03-10 14:56 <a href="http://www.blogjava.net/faithwind/articles/34669.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Velocity实例</title><link>http://www.blogjava.net/faithwind/articles/34305.html</link><dc:creator>黑咖啡</dc:creator><author>黑咖啡</author><pubDate>Wed, 08 Mar 2006 09:21:00 GMT</pubDate><guid>http://www.blogjava.net/faithwind/articles/34305.html</guid><wfw:comment>http://www.blogjava.net/faithwind/comments/34305.html</wfw:comment><comments>http://www.blogjava.net/faithwind/articles/34305.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/faithwind/comments/commentRss/34305.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/faithwind/services/trackbacks/34305.html</trackback:ping><description><![CDATA[Velocity 是一个基于 Java 的通用模板工具，来自于 jakarta.apache.org 。 
<P>Velocity 的介绍请参考 Velocity -- Java Web 开发新技术。这里是它的一个应用示例。</P>
<P>这个例子参照了 PHP-Nuke 的结构， 即所有 HTTP 请求都以 <A href="http://www.some.com/xxx/Modules?name=xxx&amp;arg1=xxx&amp;bbb=xxx">http://www.some.com/xxx/Modules?name=xxx&amp;arg1=xxx&amp;bbb=xxx</A> 的形式进行处理。例子中所有文件都是 .java 和 .html , 没有其他特殊的文件格式。除了 Modules.java 是 Java Servlet， 其余的 .java 文件都是普通的 Java Class.</P>
<P>所有 HTTP 请求都通过 Modules.java 处理。Modules.java 通过 Velocity 加载 Modules.htm。 Modules.htm 有页头，页脚，页左导航链接，页中内容几个部分。其中页头广告、页中内容是变化部分。页头广告由 Modules.java 处理，页中内容部分由 Modules.java dispatch 到子页面类处理。</P>
<P>1) Modules.java</P>
<P>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; import javax.servlet.*;<BR>import javax.servlet.http.*;<BR>import org.apache.velocity.*;<BR>import org.apache.velocity.context.*;<BR>import org.apache.velocity.exception.*;<BR>import org.apache.velocity.servlet.*;<BR>import commontools.*;</P>
<P>public class Modules<BR>　　extends VelocityServlet {<BR>　　public Template handleRequest(HttpServletRequest request,<BR>　　　　　　　　　　　　　　　　　HttpServletResponse response,<BR>　　　　　　　　　　　　　　　　　Context context) {<BR>　　　　//init<BR>　　　　response.setContentType("text/html; charset=UTF-8");<BR>　　　　response.setCharacterEncoding("utf-8");</P>
<P>　　　　//prepare function page<BR>　　　　ProcessSubPage page = null;<BR>　　　　ProcessSubPage mainPage = new HomeSubPage();<BR>　　　　String requestFunctionName = (String) request.getParameter("name");<BR>　　　　boolean logined = false;</P>
<P>　　　　String loginaccount = (String) request.getSession(true).getAttribute(<BR>　　　　　　"loginaccount");<BR>　　　　if (loginaccount != null) {<BR>　　　　　　logined = true;<BR>　　　　}</P>
<P>　　　　//default page is mainpage<BR>　　　　page = mainPage;<BR>　　　　if (requestFunctionName == null||requestFunctionName.equalsIgnoreCase("home")) {<BR>　　　　　　page = mainPage;<BR>　　　　}</P>
<P>　　　　//no login , can use these page<BR>　　　　else if (requestFunctionName.equalsIgnoreCase("login")) {<BR>　　　　　　page = new LoginProcessSubPage();<BR>　　　　}<BR>　　　　else if (requestFunctionName.equalsIgnoreCase("ChangePassword")) {<BR>　　　　　　page = new ChangePasswordSubPage();<BR>　　　　}<BR>　　　　else if (requestFunctionName.equalsIgnoreCase("ForgetPassword")) {<BR>　　　　　　page = new ForgetPassword();<BR>　　　　}<BR>　　　　else if (requestFunctionName.equalsIgnoreCase("about")) {<BR>　　　　　　page = new AboutSubPage();<BR>　　　　}<BR>　　　　else if (requestFunctionName.equalsIgnoreCase("contact")) {<BR>　　　　　　page = new ContactSubPage();<BR>　　　　}</P>
<P><BR>　　　　//for other page, need login first<BR>　　　　else if (logined == false) {<BR>　　　　　　page = new LoginProcessSubPage();<BR>　　　　}</P>
<P>　　　　else if (requestFunctionName.equalsIgnoreCase("listProgram")) {<BR>　　　　　　page = new ListTransactionProgramSubPage();<BR>　　　　}<BR>　　　　else if (requestFunctionName.equalsIgnoreCase(<BR>　　　　　　"ViewProgramItem")) {<BR>　　　　　　page = new ViewTransactionProgramItemSubPage();<BR>　　　　}<BR>　　　　else if (requestFunctionName.equalsIgnoreCase(<BR>　　　　　　"UpdateProgramObjStatus")) {<BR>　　　　　　page = new UpdateTransactionProgramObjStatusSubPage();<BR>　　　　}<BR>　　　　else if (requestFunctionName.equalsIgnoreCase(<BR>　　　　　　"Search")) {<BR>　　　　　　page = new SearchSubPage();<BR>　　　　}</P>
<P>　　　　//check if this is administrator<BR>　　　　else if (Utilities.isAdministratorLogined(request)) {<BR>　　　　　　//Utilities.debugPrintln("isAdministratorLogined : true");<BR>　　　　　　if (requestFunctionName.equalsIgnoreCase("usermanagement")) {<BR>　　　　　　　　page = new UserManagementSubPage();<BR>　　　　　　}<BR>　　　　　　else if (requestFunctionName.equalsIgnoreCase(<BR>　　　　　　　　"UploadFiles")) {<BR>　　　　　　　　page = new UploadFilesSubPage();<BR>　　　　　　}<BR>　　　　　　else if (requestFunctionName.equalsIgnoreCase(<BR>　　　　　　　　"DownloadFile")) {<BR>　　　　　　　　page = new DownloadFileSubPage();<BR>　　　　　　}<BR>　　　　　　else if (requestFunctionName.equalsIgnoreCase(<BR>　　　　　　　　"Report")) {<BR>　　　　　　　　page = new ReportSubPage();<BR>　　　　　　}</P>
<P>　　　　}<BR>　　　　else {<BR>　　　　　　//no right to access.<BR>　　　　　　//Utilities.debugPrintln("isAdministratorLogined : false");<BR>　　　　　　page = null;<BR>　　　　}<BR>　　　　//Utilities.debugPrintln("page : " + page.getClass().getName());</P>
<P>　　　　if(page != null){<BR>　　　　　　context.put("function_page",<BR>　　　　　　　　　　　　page.getHtml(this, request, response, context));<BR>　　　　}else{<BR>　　　　　　String msg = "Sorry, this module is for administrator only.You are not administrator.";<BR>　　　　　　context.put("function_page",msg);<BR>　　　　}<BR>　　　　<BR>　　　　context.put("page_header",getPageHeaderHTML());<BR>　　　　context.put("page_footer",getPageFooterHTML());</P>
<P>　　　　Template template = null;<BR>　　　　try {<BR>　　　　　　template = getTemplate("/templates/Modules.htm"); //good<BR>　　　　}<BR>　　　　catch (ResourceNotFoundException rnfe) {<BR>　　　　　　Utilities.debugPrintln("ResourceNotFoundException 2");<BR>　　　　　　rnfe.printStackTrace();<BR>　　　　}<BR>　　　　catch (ParseErrorException pee) {<BR>　　　　　　Utilities.debugPrintln("ParseErrorException2 " + pee.getMessage());<BR>　　　　}<BR>　　　　catch (Exception e) {<BR>　　　　　　Utilities.debugPrintln("Exception2 " + e.getMessage());<BR>　　　　}</P>
<P>　　　　return template;<BR>　　}</P>
<P>　　/**<BR>　　 * Loads the configuration information and returns that information as a Properties, e<BR>　　 * which will be used to initializ the Velocity runtime.<BR>　　 */<BR>　　protected java.util.Properties loadConfiguration(ServletConfig config) throws<BR>　　　　java.io.IOException, java.io.FileNotFoundException {<BR>　　　　return Utilities.initServletEnvironment(this);</P>
<P>　　}</P>
<P>}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <BR>2) ProcessSubPage.java ， 比较简单，只定义了一个函数接口 getHtml</P>
<P>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <BR>&nbsp; import javax.servlet.http.*;<BR>import org.apache.velocity.context.*;<BR>import org.apache.velocity.servlet.*;<BR>import commontools.*;</P>
<P>public abstract class ProcessSubPage implements java.io.Serializable {<BR>　　public ProcessSubPage() {<BR>　　}</P>
<P>　　public String getHtml(VelocityServlet servlet, HttpServletRequest request,<BR>　　　　　　　　　　　　　HttpServletResponse response,<BR>　　　　　　　　　　　　　Context context) {<BR>　　　　Utilities.debugPrintln(<BR>　　　　　　"you need to override this method in sub class of ProcessSubPage:"<BR>　　　　　　+ this.getClass().getName());<BR>　　　　return "Sorry, this module not finish yet.";<BR>　　}</P>
<P>}<BR>&nbsp;&nbsp; <BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </P>
<P>他的 .java 文件基本上是 ProcessSubPage 的子类和一些工具类。 ProcessSubPage 的子类基本上都是一样的流程， 用类似<BR>context.put("page_footer",getPageFooterHTML());<BR>的写法置换 .html 中的可变部分即可。如果没有可变部分，完全是静态网页，比如 AboutSubPage， 就更简单。</P>
<P>3) AboutSubPage.java</P>
<P>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <BR>&nbsp; import org.apache.velocity.servlet.VelocityServlet;<BR>import javax.servlet.http.HttpServletRequest;<BR>import javax.servlet.http.HttpServletResponse;<BR>import org.apache.velocity.context.Context;</P>
<P>public class AboutSubPage extends ProcessSubPage {<BR>　　public AboutSubPage() {<BR>　　}</P>
<P>　　public String getHtml(VelocityServlet servlet, HttpServletRequest request,<BR>　　　　　　　　　　　　　HttpServletResponse response, Context context) {<BR>　　　　//prepare data<BR>　　　　//context.put("xxx","xxxx");　　　　　　　　　<BR>　　　　　　　　　　　　　<BR>　　　　Template template = null;<BR>　　　　String fileName = "About.htm";<BR>　　　　try {<BR>　　　　　　template = servlet.getTemplate(fileName);<BR>　　　　　　StringWriter sw = new StringWriter();<BR>　　　　　　template.merge(context, sw);<BR>　　　　　　return sw.toString();<BR>　　　　}<BR>　　　　catch (Exception ex) {<BR>　　　　　　return "error get template " + fileName + " " + ex.getMessage();<BR>　　　　}<BR>　　}<BR>}<BR>&nbsp;&nbsp; <BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </P>
<P>其他 ProcessSubPage 的子类如上面基本类似，只不过会多了一些 context.put("xxx","xxxx") 的语句。 </P>
<P>通过以上的例子，我们可以看到，使用 Velocity + Servlet , 所有的代码为： 1 个 java serverlet + m 个 java class + n 个 Html 文件。</P>
<P>这里是用了集中处理，然后分发(dispatch)的机制。不用担心用户在没有登陆的情况下访问某些页面。用户验证，页眉页脚包含都只写一次，易于编写、修改和维护。代码比较简洁，并且很容易加上自己的页面缓冲功能。可以随意将某个页面的 html 在内存中保存起来，缓存几分钟，实现页面缓冲功能。成功、出错页面也可以用同样的代码封装成函数，通过参数将 Message/Title 传入即可。</P>
<P>因为 Java 代码与 Html 代码完全在不同的文件中，美工与java代码人员可以很好的分工，每个人修改自己熟悉的文件，基本上不需要花时间做协调工作。而用 JSP, 美工与java代码人员共同修改维护 .jsp 文件，麻烦多多，噩梦多多。而且这里没有用 xml ，说实话，懂 xml/xls 之类的人只占懂 Java 程序员中的几分之一，人员不好找。</P>
<P>因为所有 java 代码人员写的都是标准 Java 程序，可以用任何 Java 编辑器，调试器，因此开发速度也会大大提高。美工写的是标准 Html 文件，没有 xml, 对于他们也很熟悉，速度也很快。并且，当需要网站改版的时候，只要美工把 html 文件重新修饰排版即可，完全不用改动一句 java 代码。</P>
<P>爽死了！！</P>
<P>4) 工具类 Utilities.java </P>
<P>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <BR>&nbsp; import java.io.*;<BR>import java.sql.*;<BR>import java.text.*;<BR>import java.util.*;<BR>import java.util.Date;<BR>import javax.naming.*;<BR>import javax.servlet.*;<BR>import javax.servlet.http.*;<BR>import org.apache.velocity.*;<BR>import org.apache.velocity.app.*;<BR>import org.apache.velocity.context.Context;<BR>import org.apache.velocity.servlet.*;</P>
<P>public class Utilities {<BR>　　private static Properties m_servletConfig = null;</P>
<P>　　private Utilities() {<BR>　　}</P>
<P>　　static {<BR>　　　　initJavaMail();<BR>　　}</P>
<P>　　public static void debugPrintln(Object o) {<BR>　　　　String msg = "proj debug message at " + getNowTimeString() +<BR>　　　　　　" ------------- ";<BR>　　　　System.err.println(msg + o);<BR>　　}</P>
<P>　　public static Properties initServletEnvironment(VelocityServlet v) {<BR>　　　　// init only once<BR>　　　　if (m_servletConfig != null) {<BR>　　　　　　return m_servletConfig;<BR>　　　　}</P>
<P>　　　　//debugPrintln("initServletEnvironment....");</P>
<P>　　　　try {<BR>　　　　　　/*<BR>　　　　　　 *　call the overridable method to allow the<BR>　　　　　　 *　derived classes a shot at altering the configuration<BR>　　　　　　 *　before initializing Runtime<BR>　　　　　　 */<BR>　　　　　　Properties p = new Properties();</P>
<P>　　　　　　ServletConfig config = v.getServletConfig();</P>
<P>　　　　　　// Set the Velocity.FILE_RESOURCE_LOADED_PATH property<BR>　　　　　　// to the root directory of the context.<BR>　　　　　　String path = config.getServletContext().getRealPath("/");<BR>　　　　　　//debugPrintln("real path of / is : " + path);<BR>　　　　　　p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);</P>
<P>　　　　　　// Set the Velocity.RUNTIME_LOG property to be the file<BR>　　　　　　// velocity.log relative to the root directory<BR>　　　　　　// of the context.<BR>　　　　　　p.setProperty(Velocity.RUNTIME_LOG, path +<BR>　　　　　　　　　　　　　"velocity.log");<BR>// Return the Properties object.<BR>//return p;</P>
<P>　　　　　　Velocity.init(p);<BR>　　　　　　m_servletConfig = p;<BR>　　　　　　return p;<BR>　　　　}<BR>　　　　catch (Exception e) {<BR>　　　　　　debugPrintln(e.getMessage());<BR>　　　　　　//throw new ServletException("Error initializing Velocity: " + e);<BR>　　　　}<BR>　　　　return null;</P>
<P>　　　　//this.getServletContext().getRealPath("/");<BR>　　}</P>
<P>　　private static void initJavaMail() {<BR>　　}</P>
<P>　　public static Connection getDatabaseConnection() {<BR>　　　　Connection con = null;<BR>　　　　try {<BR>　　　　　　InitialContext initCtx = new InitialContext();<BR>　　　　　　javax.naming.Context context = (javax.naming.Context) initCtx.<BR>　　　　　　　　lookup("java:comp/env");<BR>　　　　　　javax.sql.DataSource ds = (javax.sql.DataSource) context.lookup(<BR>　　　　　　　　"jdbc/TestDB");<BR>　　　　　　//Utilities.debugPrintln("ds = " + ds);<BR>　　　　　　con = ds.getConnection();<BR>　　　　}<BR>　　　　catch (Exception e) {<BR>　　　　　　Utilities.debugPrintln("Exception = " + e.getMessage());<BR>　　　　　　return null;<BR>　　　　}<BR>　　　　//Utilities.debugPrintln("con = " + con);<BR>　　　　return con;<BR>　　}</P>
<P>　　public static java.sql.ResultSet excuteDbQuery(Connection con, String sql,<BR>　　　　Object[] parameters) {<BR>　　　　//Exception err = null;<BR>　　　　//Utilities.debugPrintln("excuteDbQuery" + parameters[0] + " ,sql=" + sql);</P>
<P>　　　　try {<BR>　　　　　　java.sql.PreparedStatement ps = con.prepareStatement(sql);<BR>　　　　　　for (int i = 0; i &lt; parameters.length; i++) {<BR>　　　　　　　　processParameter(ps, i + 1, parameters[i]);<BR>　　　　　　}<BR>　　　　　　return ps.executeQuery();<BR>　　　　}<BR>　　　　catch (Exception e) {<BR>　　　　　　//Utilities.debugPrintln(e.getMessage());<BR>　　　　　　e.printStackTrace();<BR>　　　　}<BR>　　　　return null;<BR>　　}</P>
<P>　　public static void excuteDbUpdate(String sql, Object[] parameters) {<BR>　　　　Connection con = Utilities.getDatabaseConnection();<BR>　　　　excuteDbUpdate(con, sql, parameters);<BR>　　　　closeDbConnection(con);<BR>　　}</P>
<P>　　public static void excuteDbUpdate(Connection con, String sql,<BR>　　　　　　　　　　　　　　　　　　　Object[] parameters) {<BR>　　　　Exception err = null;<BR>　　　　try {<BR>　　　　　　java.sql.PreparedStatement ps = con.prepareStatement(sql);<BR>　　　　　　for (int i = 0; i &lt; parameters.length; i++) {<BR>　　　　　　　　processParameter(ps, i + 1, parameters[i]);<BR>　　　　　　}<BR>　　　　　　ps.execute();<BR>　　　　}<BR>　　　　catch (Exception e) {<BR>　　　　　　err = e;<BR>　　　　　　//Utilities.debugPrintln(err.getMessage());<BR>　　　　　　e.printStackTrace();<BR>　　　　}<BR>　　}</P>
<P>　　private static void processParameter(java.sql.PreparedStatement ps,<BR>　　　　　　　　　　　　　　　　　　　　 int index, Object parameter) {<BR>　　　　try {<BR>　　　　　　if (parameter instanceof String) {<BR>　　　　　　　　ps.setString(index, (String) parameter);<BR>　　　　　　}<BR>　　　　　　else {<BR>　　　　　　　　ps.setObject(index, parameter);<BR>　　　　　　}<BR>　　　　}<BR>　　　　catch (Exception e) {<BR>　　　　　　//Utilities.debugPrintln(e.getMessage());<BR>　　　　　　e.printStackTrace();<BR>　　　　}<BR>　　}</P>
<P>　　public static void closeDbConnection(java.sql.Connection con) {<BR>　　　　try {<BR>　　　　　　con.close();<BR>　　　　}<BR>　　　　catch (Exception e) {<BR>　　　　　　Utilities.debugPrintln(e.getMessage());<BR>　　　　}<BR>　　}</P>
<P>　　public static String getResultPage(<BR>　　　　String title, String message, String jumpLink,<BR>　　　　VelocityServlet servlet, HttpServletRequest request,<BR>　　　　HttpServletResponse response, Context context) {</P>
<P>　　　　Template template = null;</P>
<P>　　　　context.put("MessageTitle", title);<BR>　　　　context.put("ResultMessage", message);<BR>　　　　context.put("JumpLink", jumpLink);</P>
<P>　　　　try {<BR>　　　　　　template = servlet.getTemplate(<BR>　　　　　　　　"/templates/Message.htm");<BR>　　　　　　StringWriter sw = new StringWriter();<BR>　　　　　　template.merge(context, sw);<BR>　　　　　　return sw.toString();<BR>　　　　}<BR>　　　　catch (Exception ex) {<BR>　　　　　　return "error get template Message.htm " + ex.getMessage();<BR>　　　　}</P>
<P>　　}</P>
<P>　　public static String mergeTemplate(String fileName, VelocityServlet servlet,<BR>　　　　　　　　　　　　　　　　　　　 Context context) {<BR>　　　　Template template = null;</P>
<P>　　　　try {<BR>　　　　　　template = servlet.getTemplate(fileName);<BR>　　　　　　StringWriter sw = new StringWriter();<BR>　　　　　　template.merge(context, sw);<BR>　　　　　　return sw.toString();<BR>　　　　}<BR>　　　　catch (Exception ex) {<BR>　　　　　　return "error get template " + fileName + " " + ex.getMessage();<BR>　　　　}<BR>　　}</P>
<P>}</P>
<P>&nbsp;&nbsp; </P><img src ="http://www.blogjava.net/faithwind/aggbug/34305.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/faithwind/" target="_blank">黑咖啡</a> 2006-03-08 17:21 <a href="http://www.blogjava.net/faithwind/articles/34305.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>