`
wangpx
  • 浏览: 203537 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

模板:velocity和freemarker的比较[转

    博客分类:
  • java
阅读更多

关键字: 模板技术

/**
*作者:张荣华(ahuaxuan)
*2007-04-16
*转载请注明出处及作者
*/

模板技术在现代的软件开发中有着重要的地位,而目前最流行的两种模板技术恐怕要算freemarker和velocity velocity 作为view,模板技术作为view的好处是很多,尤其和jsp 比较起来优点更大,众所周知jsp 需要在第一次被执行的时候编译成servlet,那么这个过程是很慢的,当然很多应用服务器都提供预编译的功能,但是在开发的时候仍然给我们程序员带来了很多痛苦,每次修改都要多几秒钟,那在一天的开发中就有很多时间浪费在jsp 的编译上了。用webwork in action的作者的话来说:“每次修改之后重新运行都要等等几秒是令人失望的,而频繁地修改jsp 更是会令你的失望情绪变本加厉“。我们把模板技术引入到view中去可以带来更好的开发效率,而且模板的速度要比jsp 快(虽然编译过后的jsp 在速度上已经满足我的需求了,呵呵)。 当然模板技术可以用在很多领域,可不只在view那里。我们可以通过模板技术来生成xml,生成jsp ,生成java文件等等,说到这里,大家通常会使用模板技术用在公司的框架里,这样就可以很快速的生成添删改查的代码,需要的只是模板,其他比如还有邮件模板等等。

以上是模板的作用,当然模板还有其他领域的应用,希望能和大家多讨论,提高我们的生产效率。

那么现在开源的模板技术有好几种,多了之后就有一个选择的问题了,如何选择一个满足自己需要的模板的呢,我大概了看了一下两种模板技术,写了一个例子,我使用了几种设计模式来完成了这个例子,这个例子中,我同时使用了freemarker和velocity ,这样同学们可以通过代码很直观的比较两种模板技术,通过这个例子,我认识到freemarker在功能上要比velocity 强大
1在view层的时候,它提供了format日期和数字的功能,我想大家都有在页面上format日期或数字的经验,用jsp 的同学可能对jstl的fmt标签很有感情,使用了freemarker之后也可以使用freemarker提供的功能来formmat日期和数据,这个功能我想是很贴心的

2通过我的使用我发现freemaker的eclipseplugin要比velocity 的eclipseplugin好,如果你是用idea那很遗憾,我没有找到类似的插件。好在很多地方呢,我看到的是freemarker的插件除了支持freemarker语法也支持html语句,而velocity 的插件貌似只支持velocity 的语法,html就只是用普通的文本来显示了,在这一点上freemarker占上风了(不要和我说高手都是用windows记事本之类的话,这本来就违背了模板技术的初衷)

3freemarker对jsptag的支持很好,算了,不到迫不得已还是不要这样做吧。

还有就是两者的语法格式,这一点上不同的人有不同倾向

下面就介绍一下这个例子吧
了,webwork2.2对两者都有不错的支持,也就是说在webwork2中你可以随意选择使用freemarker或

Java代码 复制代码
  1. /**  
  2.  *   
  3.  * @author 张荣华  
  4.  * 转载请注明出处  
  5.  */   
  6. public   class  TemplateTest {   
  7.   
  8.      /**  
  9.      * @param args  
  10.      */   
  11.      public   static   void  main(String[] args)  throws  Exception{   
  12.          /* 准备数据 */   
  13.         Map latest =  new  HashMap();   
  14.         latest.put( "url" "products/greenmouse.html" );   
  15.         latest.put( "name" "green mouse" );   
  16.            
  17.         Map root =  new  HashMap();   
  18.         root.put( "user" "Big Joe" );   
  19.         root.put( "latestProduct" , latest);   
  20.         root.put( "number" new  Long( 2222 ));   
  21.         root.put( "date" , new  Date());   
  22.            
  23.         List listTest =  new  ArrayList();   
  24.         listTest.add( "1" );   
  25.         listTest.add( "2" );   
  26.            
  27.         root.put( "list" ,listTest);   
  28.            
  29.         TemplateEngine freemarkerEngine = (TemplateEngine)TemplateFactory.getInstance().getBean( "freemarker" );   
  30.         freemarkerEngine.run(root); //使用freemarker模板技术   
  31.            
  32.         TemplateEngine velocityEngine = (TemplateEngine)TemplateFactory.getInstance().getBean( " velocity " );   
  33.         velocityEngine.run(root); //使用 velocity 模板技术   
  34.     }   
  35.   
  36. }  
/**
 * 
 * @author 张荣华
 * 转载请注明出处
 */
public class TemplateTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		/* 准备数据 */
        Map latest = new HashMap();
        latest.put("url", "products/greenmouse.html");
        latest.put("name", "green mouse");
        
        Map root = new HashMap();
        root.put("user", "Big Joe");
        root.put("latestProduct", latest);
        root.put("number", new Long(2222));
        root.put("date",new Date());
        
        List listTest = new ArrayList();
        listTest.add("1");
        listTest.add("2");
        
        root.put("list",listTest);
        
        TemplateEngine freemarkerEngine = (TemplateEngine)TemplateFactory.getInstance().getBean("freemarker");
        freemarkerEngine.run(root);//使用freemarker模板技术
        
        TemplateEngine velocityEngine = (TemplateEngine)TemplateFactory.getInstance().getBean("velocity


velocity




");
        velocityEngine.run(root);//使用
模板技术
	}

}



工厂类,用来得到模板引擎

Java代码 复制代码
  1. /**  
  2.  *   
  3.  * @author 张荣华  
  4.  * 转载请注明出处  
  5.  */   
  6. public   class  TemplateFactory {   
  7.      private   static  TemplateFactory instance;   
  8.      private  Map objectMap;   
  9.        
  10.      static {   
  11.         instance =  new  TemplateFactory();   
  12.     }   
  13.        
  14.      public  TemplateFactory() {   
  15.          super ();   
  16.          this .objectMap =  new  HashMap();   
  17.          synchronized  ( this ) {   
  18.             objectMap.put( "freemarker" new  FreemarkerTemplateEngine(){   
  19.                  public  String getTemplatePath() {   
  20.                      return   "template" ;   
  21.                 }   
  22.             });   
  23.                
  24.             objectMap.put( " velocity " new  VelocityTemplateEngine());   
  25.         }   
  26.     }   
  27.   
  28.      public   static  TemplateFactory getInstance(){   
  29.          return  instance;   
  30.     }   
  31.        
  32.      /**  
  33.      * 模仿spring的工厂  
  34.      * @param beanName  
  35.      * @return  
  36.      */   
  37.      public  Object getBean(String beanName){   
  38.          return  objectMap.get(beanName);   
  39.     }   
  40.   
  41. }  
/**
 * 
 * @author 张荣华
 * 转载请注明出处
 */
public class TemplateFactory {
	private static TemplateFactory instance;
	private Map objectMap;
	
	static{
		instance = new TemplateFactory();
	}
	
	public TemplateFactory() {
		super();
		this.objectMap = new HashMap();
		synchronized (this) {
			objectMap.put("freemarker", new FreemarkerTemplateEngine(){
				public String getTemplatePath() {
					return "template";
				}
			});
			
			objectMap.put("velocity




", new VelocityTemplateEngine());
		}
	}

	public static TemplateFactory getInstance(){
		return instance;
	}
	
	/**
	 * 模仿spring的工厂
	 * @param beanName
	 * @return
	 */
	public Object getBean(String beanName){
		return objectMap.get(beanName);
	}

}

引擎接口

Java代码 复制代码
  1. /**  
  2.  *   
  3.  * @author 张荣华  
  4.  * 转载请注明出处  
  5.  */   
  6. public   interface  TemplateEngine {   
  7.        
  8.      void  run(Map context) throws  Exception;   
  9.   
  10. }  
/**
 * 
 * @author 张荣华
 * 转载请注明出处
 */
public interface TemplateEngine {
	
	void run(Map context)throws Exception;

}

模板引擎的实现使用method template模式,因为有两个实现,这两个实现又存在公共的逻辑,所以选择了这个模式

Java代码 复制代码
  1. /**  
  2.  *   
  3.  * @author 张荣华  
  4.  * 转载请注明出处  
  5.  */   
  6. public   abstract   class  AbstractTemplateEngine  implements  TemplateEngine{   
  7.   
  8.      public   abstract  String getTemplatePath();   
  9.        
  10.      public   abstract  String getTemplate();   
  11.        
  12.      public   abstract  String getEngineType();   
  13.        
  14.      public   void  run(Map context) throws  Exception{   
  15.          if (Constants.ENGINE_TYPE_FREEMARKER.equals(getEngineType()))   
  16.             executeFreemarker(context);   
  17.          else   
  18.             executeVelocity(context);   
  19.     }   
  20.        
  21.      private   void  executeFreemarker(Map context) throws  Exception{   
  22.         Configuration cfg =  new  Configuration();   
  23.         cfg.setDirectoryForTemplateLoading(   
  24.                  new  File(getTemplatePath()));   
  25.         cfg.setObjectWrapper( new  DefaultObjectWrapper());   
  26.            
  27.         cfg.setCacheStorage( new  freemarker.cache.MruCacheStorage( 20 250 ));   
  28.                    
  29.         Template temp = cfg.getTemplate(getTemplate());   
  30.   
  31.         Writer out =  new  OutputStreamWriter(System.out);   
  32.         temp.process(context, out);   
  33.         out.flush();   
  34.     }   
  35.        
  36.      private   void  executeVelocity(Map root) throws  Exception{   
  37.            
  38.         Velocity .init();   
  39.         VelocityContext context =  new  VelocityContext(root);   
  40.         org.apache.velocity .Template template =  null ;   
  41.            
  42.         template = Velocity .getTemplate(getTemplatePath()+getTemplate());   
  43.            
  44.         StringWriter sw =  new  StringWriter();   
  45.         template.merge( context, sw );   
  46.         System.out.print(sw.toString());   
  47.   
  48.     }   
  49.   
  50. }  
/**
 * 
 * @author 张荣华
 * 转载请注明出处
 */
public abstract class AbstractTemplateEngine implements TemplateEngine{

	public abstract String getTemplatePath();
	
	public abstract String getTemplate();
	
	public abstract String getEngineType();
	
	public void run(Map context)throws Exception{
		if(Constants.ENGINE_TYPE_FREEMARKER.equals(getEngineType()))
			executeFreemarker(context);
		else
			executeVelocity(context);
	}
	
	private void executeFreemarker(Map context)throws Exception{
		Configuration cfg = new Configuration();
	    cfg.setDirectoryForTemplateLoading(
	            new File(getTemplatePath()));
	    cfg.setObjectWrapper(new DefaultObjectWrapper());
	    
	    cfg.setCacheStorage(new freemarker.cache.MruCacheStorage(20, 250));
	            
	    Template temp = cfg.getTemplate(getTemplate());

	    Writer out = new OutputStreamWriter(System.out);
	    temp.process(context, out);
	    out.flush();
	}
	
	private void executeVelocity(Map root)throws Exception{
		
		Velocity


velocity


Velocity




.init();
		VelocityContext context = new VelocityContext(root);
		org.apache.
.Template template = null;
		
	    template = 
.getTemplate(getTemplatePath()+getTemplate());
	    
		StringWriter sw = new StringWriter();
		template.merge( context, sw );
		System.out.print(sw.toString());

	}

}




这个是freemarker实现

Java代码 复制代码
  1. /**  
  2.  *   
  3.  * @author 张荣华  
  4.  * 转载请注明出处  
  5.  */   
  6. public   class  FreemarkerTemplateEngine  extends  AbstractTemplateEngine{   
  7.      private   static   final  String DEFAULT_TEMPLATE =  "FreemarkerExample.ftl" ;   
  8.        
  9.      /**  
  10.      * 这个方法应该实现的是读取配置文件  
  11.      */   
  12.      public  String getTemplatePath() {   
  13.          return   null ;   
  14.     }   
  15.        
  16.      public   void  run(Map root)  throws  Exception{   
  17.          super .run(root);   
  18.     }   
  19.   
  20.      public  String getTemplate() {   
  21.          // TODO Auto-generated method stub   
  22.          return  DEFAULT_TEMPLATE;   
  23.     }   
  24.   
  25.      public  String getEngineType() {   
  26.          return  Constants.ENGINE_TYPE_FREEMARKER;   
  27.     }   
  28. }  
/**
 * 
 * @author 张荣华
 * 转载请注明出处
 */
public class FreemarkerTemplateEngine extends AbstractTemplateEngine{
	private static final String DEFAULT_TEMPLATE = "FreemarkerExample.ftl";
	
	/**
	 * 这个方法应该实现的是读取配置文件
	 */
	public String getTemplatePath() {
		return null;
	}
	
	public void run(Map root) throws Exception{
		super.run(root);
	}

	public String getTemplate() {
		// TODO Auto-generated method stub
		return DEFAULT_TEMPLATE;
	}

	public String getEngineType() {
		return Constants.ENGINE_TYPE_FREEMARKER;
	}
}

这个是velocity 实现

Java代码 复制代码
  1. /**  
  2.  *   
  3.  * @author 张荣华  
  4.  * 转载请注明出处  
  5.  */   
  6. public   class  VelocityTemplateEngine  extends  AbstractTemplateEngine{   
  7.   
  8. private   static   final  String DEFAULT_TEMPLATE =  "VelocityExample.vm" ;   
  9.   
  10.      public  String getTemplatePath() {   
  11.          return   "/template/" ;   
  12.     }   
  13.        
  14.      public   void  run(Map map)  throws  Exception{   
  15.          super .run(map);   
  16.     }   
  17.   
  18.      public  String getTemplate() {   
  19.          // TODO Auto-generated method stub   
  20.          return  DEFAULT_TEMPLATE;   
  21.     }   
  22.   
  23.      public  String getEngineType() {   
  24.          // TODO Auto-generated method stub   
  25.          return  Constants.ENGINE_TYPE_VELOCITY;   
  26.     }   
  27. }  
/**
 * 
 * @author 张荣华
 * 转载请注明出处
 */
public class VelocityTemplateEngine extends AbstractTemplateEngine{

private static final String DEFAULT_TEMPLATE = "VelocityExample.vm";

	public String getTemplatePath() {
		return "/template/";
	}
	
	public void run(Map map) throws Exception{
		super.run(map);
	}

	public String getTemplate() {
		// TODO Auto-generated method stub
		return DEFAULT_TEMPLATE;
	}

	public String getEngineType() {
		// TODO Auto-generated method stub
		return Constants.ENGINE_TYPE_VELOCITY;
	}
}



以下是模板
1,freemarker模板

Java代码 复制代码
  1. freemarker template test:   
  2. string test-----------${user}-----------${number}-----------${latestProduct.url}-----------${latestProduct.name}   
  3. condition test-----------   
  4. <# if  user ==  "Big Joe" >   
  5. list iterator-----------   
  6. <#list list as aa>   
  7. ${aa}   
  8. </#list>    
  9. </# if >   
  10. date test-----------${date?string( "MMM/dd/yyyy" )}  
freemarker template test:
string test-----------${user}-----------${number}-----------${latestProduct.url}-----------${latestProduct.name}
condition test-----------
<#if user == "Big Joe">
list iterator-----------
<#list list as aa>
${aa}
</#list> 
</#if>
date test-----------${date?string("MMM/dd/yyyy")}



2,velocity 模板

Java代码 复制代码
  1. ******************************************************************************************************************   
  2. velocity  template test:   
  3. string test-----------${user}-----------${number}-----------${latestProduct.url}-----------${latestProduct.name}   
  4. condition test-----------   
  5. # if  ($user ==  "Big Joe" )   
  6. list iterator-----------   
  7. #foreach( $aa in $list )   
  8. $aa   
  9. #end   
  10. #end   
  11. date test-----------${date}  
******************************************************************************************************************
velocity




 template test:
string test-----------${user}-----------${number}-----------${latestProduct.url}-----------${latestProduct.name}
condition test-----------
#if ($user == "Big Joe")
list iterator-----------
#foreach( $aa in $list )
$aa
#end
#end
date test-----------${date}



至此整个例子就结束了,以上只是最简单的介绍,当然这两种技术还有待我们的深入研究。这个例子只不过是比较直观的表现两种技术的使用而已
而且如果想学习方法模板模式和工厂模式的同学可以下载代码看看

作者:张荣华,未经作者同意不得随意转载!

分享到:
评论

相关推荐

    模板:velocity和freemarker的比较

    Velocity和Freemarker模板技术比较 模板技术在现代软件开发中扮演着重要角色,而在目前最流行的两种模板技术中, Velocity 和 Freemarker 独占鳌头。在 WebWork2 中,我们可以随意选择使用 Freemarker 或 Velocity ...

    velocity和freemarker的比较

    以上是对Velocity和FreeMarker的基本介绍和比较,它们都是Java Web开发中的重要工具,理解它们的特性和应用场景有助于选择最适合项目的技术栈。对于标签“源码”和“工具”,我们可以进一步研究这两个模板引擎的源...

    Velocity 和 FreeMarker区别

    在众多模板引擎中,Velocity和FreeMarker是两种非常受欢迎的选择。下面我们将从多个方面对这两种模板引擎进行详细的比较。 #### 一、简介 - **Velocity**:是一个基于Java的模板引擎,它允许开发者使用简单的模板...

    jsp、freemarker、velocity简介和对比

    本文将重点介绍三种常用的Java Web模板引擎:JSP(Java Server Pages)、Freemarker以及Velocity,并对它们进行深入比较。 #### JSP (Java Server Pages) JSP是一种基于Java技术的服务器端动态网页技术,通过在...

    当前流行的模板引擎效率分析(velocity,freeMarker,Smarty4j,httl)

    本篇文章将对四个流行的Java模板引擎——Velocity、FreeMarker、Smarty4j以及HTTL进行效率分析,旨在探讨它们在处理业务逻辑编译和性能方面的优劣。 1. Velocity: Velocity是Apache软件基金会的一个开源项目,以其...

    freemarker&velocity的使用

    Freemarker和Velocity是两种广泛使用的模板引擎,它们在Java Web开发中扮演着重要的角色,主要用于生成动态HTML或其他格式的文本。这两者都是基于MVC(Model-View-Controller)设计模式,允许开发者将业务逻辑与展示...

    velocity document

    虽然Velocity和Freemarker都是视图模板引擎,但它们有各自的特性和优缺点: 1. **语法简洁性**:Freemarker的语法可能更为简洁,如其使用`&lt;#if&gt;`、`&lt;#foreach&gt;`等,而Velocity则使用`#if`、`#foreach`。 2. **灵活...

    Freemarker和Velocity的eclipse插件

    例如,Freemarker插件可以帮助快速定位模板中的语法错误,而Velocity插件则可以提供模板变量和方法的智能提示,减少出错的可能性。 总的来说,Freemarker和Velocity的Eclipse插件对于Java Web开发者来说是必不可少...

    velocity模板引擎

    - **include与parse**:为了实现页面布局的模块化,Velocity提供了`#include`和`#parse`两种方式来引入其他模板文件。`#include`主要用于简单地插入另一个文件的内容而不执行其中的Velocity语法;`#parse`则不仅会...

    Velocity介紹

    Velocity、Freemarker和Thymeleaf都是Java领域的模板引擎,它们各有特点。Freemarker语法更为复杂,但功能更强大;Thymeleaf强调的是XML友好的语法,更适合静态页面的生成。Velocity则以其简洁和易用性受到许多...

    大型商城网站springmvc+freemarker+velocity+ibatis

    标题 "大型商城网站springmvc+freemarker+velocity+ibatis" 暗示了这是一个基于SpringMVC、Freemarker、Velocity和iBatis框架构建的电子商务平台。这个项目可能是一个B2C(Business-to-Consumer)类型的商城,允许...

    velocity freemarke 模版 静态化 实现

    Velocity和FreeMarker是两种常用的Java模板引擎,它们可以方便地结合JSP(JavaServer Pages)进行动态网页生成,并实现页面静态化。本文将详细介绍如何使用Velocity和FreeMarker模板实现页面静态化,并提供具体的...

    Velocity用户手册(中文)

    4. **Freemarker**: 虽然Velocity和Freemarker都是模板引擎,但它们各有特点,可以根据项目需求选择合适的工具。 总之,Velocity作为一款强大的模板引擎,对于Web开发中的前后端分离有着重要作用,它的简单性和灵活...

    velocity的所有jar包

    Velocity是一个开源的Java模板引擎,它允许开发者将HTML与Java代码分离,使Web开发者...对于新项目,考虑使用更新的版本(如Velocity 2.x)或者其他的模板引擎,如FreeMarker或Thymeleaf,可能会带来更多的优势和功能。

    Velocity--java的模板引擎

    Velocity与JSP、FreeMarker等其他模板引擎相比,有其独特优势。Velocity的语法简洁,更接近自然语言,且由于它不支持脚本,避免了在模板中引入过多的业务逻辑,使得模板更加纯粹。此外,Velocity的性能也相对较高,...

    基于Freemarker模板的代码生成器后台代码(controller,service,dao)模板文件

    这个压缩包提供的就是一套基于Freemarker模板的代码生成器模板文件,分别对应控制器(Controller)、实体类(Bean)、服务接口(Service)和服务实现(ServiceImpl)、数据访问对象(Dao)。 1. **Controller.ftl**...

    freemarker导出Excel、Word、HTMLdemo

    在Java中,Freemarker与ModelAndView、Velocity等模板引擎类似,它通过模板语言(Template Language)来描述数据如何被渲染。下面我们将详细探讨如何使用Freemarker来导出Excel、Word和HTML。 1. **导出Excel** - ...

    SpringMVC模板 

    在这个话题中,我们将深入探讨SpringMVC与两种常用的模板引擎——Velocity和FreeMarker的集成与应用。 首先,让我们了解SpringMVC的基本架构。在SpringMVC中,DispatcherServlet是入口点,它负责接收HTTP请求并根据...

Global site tag (gtag.js) - Google Analytics