Velocity之Web实践

    之前的文章《Velocity初体验》,介绍了Velocity的工作原理和一些演示样例,但有朋友觉得不和Web结合起来针对性不够突出,所以下面结合Web开发来进一步说明,Velocity+Servlet+JavaBean)是怎样工作的。

通过下面的说明,仅提出VelocityWeb方面的简单示例,为大家献上一个原始但清晰的认识,来了解VelocityWeb方面的工作原理,未来还有深入的主题贡献给大家。

Web环境要求Tomcat,我是用5.5版本。

首先我们还是使用VTLVelocity Template Language)编一个.vm模版,考察在网页设计师的角度是不是很容易理解和编辑,首先创建sample.vm内容如下:

< html >
   < head >< title > Velocity </ title ></ head >
   < body bgcolor = " #ffffff " >
     < center >
     < h2 > Welcom to Velocity !</ h2 >
     < i > Here ' s the list of people</i>
     < table cellspacing = " 0 "  cellpadding = " 5 "  width = " 20% "   >
     < tr >
     < td bgcolor = " #eeeeee "  align = " center " >
    Names

     </ td >
     </ tr >
    #foreach ($name in $theList)
     < tr >
     < td bgcolor = " #eeeeee "  align = " center " > $name </ td >
     </ tr >
    #end
     </ table >
     </ center >
   </ body >
</ html >  


然后打开FrontPage(或其他类似工具)网页编辑器,点击"工具-选项-配置编辑器",上面列出了FrontPage能打开的文件,点击添加,填入文件类型:vm,编辑器名称:FrontPage,命令:C:/Program Files/Microsoft Office/Office/frontpg.exeFrontPage运行的完整路径,可从已有的文件类型中Copy出完整路径),点击打开界面的确定后,我们从FrontPage的文件菜单中选择打开文件,选择上面新建的sample.vm,怎么样,编辑、预览和修改都一目了然吧(如下图),即使不清楚VTL的,也可以通过简单的手册查询知道(一般都不会用到吧),这样对于网页设计师、开发人员和维护人员来说,都是很容易的事。而如果你使用了一些开发工具,如Jbuilder则在toolsproference的编辑类型里,在Html档增加.vm的支持,则就可以进行编辑和用html预览器预览了,其他的开发工具自己摸索吧。

 

接下来看看最简单的Servlet是怎么和Velocity结合工作的,创建SampleServlet.java,由于VelocityServlet提供了统一的Servlet入口和封装了大部分工作,以及把展示数据合并到模版中,所以SampleServlet通过继承VelocityServlet,工作将简便很多,代码如下:

package  com.javayou.velocity.servlet;

/**/
/*

 * @author Liang.xf 2004-12-15
 * Velocity + Servlet 
演示
 * www.javayou.com
 
*/

import
 java.io.IOException;
import
 java.io.FileNotFoundException;

import
 java.util.Properties;
import
 java.util.Vector;

import
 javax.servlet.ServletConfig;
import
 javax.servlet.http.HttpServletRequest;
import
 javax.servlet.http.HttpServletResponse;

import
 org.apache.velocity.Template;
import
 org.apache.velocity.context.Context;
import
 org.apache.velocity.servlet.VelocityServlet;
import
 org.apache.velocity.app.Velocity;
import
 org.apache.velocity.exception.ResourceNotFoundException;
import
 org.apache.velocity.exception.ParseErrorException;

public   class  SampleServlet  extends
 VelocityServlet  {
     /** */
/**

     *   
VelocityServlet.init()调用, We want to set a set of properties
     *   
在此找出模版的路径

     
*/
    
protected
 Properties loadConfiguration(ServletConfig config )
        
throws
 IOException, FileNotFoundException  {
        Properties p  =  
new
 Properties();
         /**/
/*

         *  first, we set the template path for the
         *  FileResourceLoader to the root of the 
         *  webapp.  This probably won't work under
         *  in a WAR under WebLogic, but should 
         *  under tomcat :)
         
*/
        String path  =  config.getServletContext().getRealPath( " / " );

        
if  (path  ==   null
{
            System.out.println( "  SampleServlet.loadConfiguration() : unable to  "  
                     +   " get the current webapp root.  Using '/'. Please fix. " );
            path  =   " / " ;
        }

        p.setProperty( Velocity.FILE_RESOURCE_LOADER_PATH,  path );
        
// 同样设置log

        p.setProperty(  " runtime.log " , path  +   " velocity.log "  );
        
return
 p;
    }

     /** */
/**

     *  Velocity
主要的商业逻辑处理方法,由VelocityServlet自动调用
     *  
@param  ctx a Velocity Context object to be filled with
     *             data.  Will be used for rendering this 
     *             template
     *  
@return
 Template to be used for request
     
*/
   
    
public
 Template handleRequest( HttpServletRequest request,
       HttpServletResponse response, Context ctx )  {
        
        
// 主要在此设置演示用的数据,开发中在此调用相应的业务处理流程,


        
//        并设置返回到页面的数据
        
        System.out.println( " ------SampleVelocity.handleRequest------- " );
        
// 待展示的列表数据

        String p1  =   " 第一位:LiuDong " ;
        String p2  =   "
第二位:
Liang.xf " ;
        Vector personList  =  
new
 Vector();
        
// 中文需要转换

         try   {
            personList.addElement(
new
 String(p1.getBytes(),  " ISO-8859-1 " ) );
            personList.addElement(
new
 String(p2.getBytes(),  " ISO-8859-1 " ) );
        }  
catch
 (Exception e)  {
            System.out.println( "
数据转换异常:
" + e);    
        }
        
// 设置数据,供页面模版替换成显示的数据

        ctx.put( " theList " , personList );        
         /**/
/*

         *  get the template.  There are three possible
         *  exceptions.  Good to know what happened.
         
*/
        Template outty  =  
null
;        
        
try
  {
            outty  =   getTemplate( " sample.vm " );
        }  
catch
( ParseErrorException pee )  {
            System.out.println( " SampleServlet: parse error for template  "   +  pee);
        }  
catch
( ResourceNotFoundException rnfe )  {
            System.out.println( " SampleServlet: template not found  "   +  rnfe);
        }  
catch
( Exception e ) {
            System.out.println( " Error  "   +  e);
        }
        
return
 outty;
    }
}

 

编译需要velocity-1.4.jarj2ee.jar,这里演示手工编译命令(所有资源放在同一目录):
javac -classpath ./velocity-1.4.jar;./j2ee.jar SampleServlet.java

编译通过后,我们接着需要发布了,以Tomcat5.5为例,新建Web应用简易说明如下:
1
/tomcat55/webapps目录下新建目录test,把上述sample.vm Copytest目录,在test内新建目录WEB-INF,在WEB-INF内分别新建目录:classeslib,在WEB-INF目录下新建文件web.xml,内容:

<? xml version = " 1.0 "  encoding = " ISO-8859-1 " ?>
< web - app >
   < display - name > Welcome to Javayou.com </ display - name >
   < servlet >
      < servlet - name > SampleServlet </ servlet - name >
      < servlet -
class > com.javayou.velocity.servlet.SampleServlet </ servlet - class
>
   </ servlet >
   < servlet - mapping >
       < servlet - name > SampleServlet </ servlet - name >
       < url - pattern >/ SampleServlet </ url - pattern >
   </ servlet - mapping >
</ web - app >

2、在classes内建立类包目录:com/javayou/velocity/servlet/copy上面编译后的SampleServlet.class
3
、在lib目录内分别copy进:commons-collections.jarlogkit-1.0.1.jarvelocity-1.4.jar
OK
Tomcat运行环境搭建完毕。
启动Tomcat,在IE上输入:http://localhost:8080/test/SampleServlet,页面显示和数据列表:第一位:LiuDong、第二位:Liang.xf 2正确,大功告成!
注意上面的显示数据含中文,所以在设置进装载容器时注意进行编码,稍显麻烦,这可以用更自动化的办法,如使用Util工具类等。
以上看来Servlet+Velocity的结合还是挺容易和简单的,而至于引伸到Servlet+Velocity+JavaBean 也不是很困难的事,稍为扩展即可达到,在这里就不再多述。

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值