JSP Velocity Freemarker comparison

JSP has been the De facto standard for Java and web development for years. JSP is one of the first popular dynamic web application frameworks. Since then as architecture models have evolved. PHP has taken a foothold in the simple dynamic web applications and large enterprise application with complex business logic has moved to MVC design using Java or .Net. Where does that leave JSP and how does it compare with Velocity and Freemarker? 

JSP Overview 
Originally, Java Server Pages were designed to be utilized within a J2EE web container that would allow for full application development. Older applications were designed to be written to directly access the JSP files. This is the MVC model 1 architecture approach. The client directly references the JSP page, the JSP page references a bean which in turn can access database information. With today's standards, however, it is typically not acceptable to utilize JSP as an independent architecture solution. As software architecture has evolved and design patterns have changed, it seems that the purposes of JSP pages have changed as well. 

The ability of JSP to permit scripting, tags, and html code makes it as powerful as Java itself with the capability to be directly run as a web page. To rebuttal the strength of this point, this unrestricted ability of allowing so many different development techniques is simply dangerous. It becomes dangerous to both the application architecture and to the average developer as it is very easy to introduce inconsistency in design patterns into the JSP. The complexity of JSP can grow quickly and further development or ongoing maintenance could suffer in both time and cost. 

An example of abusive JSP development can occur when mixing different JSP syntax. Using an particular tag library with with an expression or using ETL inside and outside of tags. JSP Scriplets are in violation of the MVC approach when using JSP as a view component which is the primary function JSP pages are used today. 

Veloctiy and Freemarker Overview 
Velocity and Freemarker are template engines that define a template language in which to parse. They take Java objects and merge the data with the template. Velocity and Freemarker are so similar I will not compare one to the other. Both are active projects. Velocity recently came out of its shell after a few slow years and had some releases in 2007. Freemarker may have a few bit more functionality than velocity but is also a bit more complex. 

JSP vs Template Engines 

    * Compile Time - JSP need to be processed and compiled to before it is executed. JSP file is converted to a Java file. It is then compiled into a class file. Both velocity and freemarker do not need compiliation. This is especially beneficial to a developer. Everytime a developer modifies a JSP it is very slow to run it due to compilation. The Velocity engine is named Velocity for a reason. 
    * Learning Curve - JSP is very large with many tag different libraries. Velocity and Freemarker are simple. The engine and core functionality can be understood within a matter of hours. 
    * Readibility - JSP allows for tag libraries, scriplets, expression language, and other various techniques that is recognized as code. Velocity uses a short list of built in commands. 
    * Community Base - Many developers know JSP. It is a very common language for developers to list as a skill. Both freemarker and velocity have a large user base but neither is as large as JSP. This is because JSP was originally used as a full application framework when deployed to a compliant web container. 
    * Template structure - JSP allows for many different types of syntax. Scripting techniques such as declarations, scriptlets, and expressions as well as actions and tags. Velocity uses a #command for commands and $var for variables. Freemarker uses <#command> for commands and ${var} for variables. JSP 2.0 tries to appear as template engine with ${} trying to resemble template style 
    * Custom Tools - JSP allows for the creation of JSP taglibs. Both Freemarker and Velocity allow the utilization of JSP taglibs as well. Freemarker has a lot of extra built in functionality as well. Velocity allows the developer to create their own custom tools. These tools are created in Java and utilized as Java objects within the template. 
    * Integration - Most of the major libraries and development tools integrate with JSP, Velocity and Freemarker. Frameworks such as Sitemesh, Tiles, Struts, and Spring have functionality available to utilize all 3 technologies.

there are couple of things where FreeMarker might suit you better: 

1. This is subjective, but the overall syntax is less awkward. I’m aware there’s lot of syntacic sugar in JSP 2.0 that’s aimed at hiding the ugliness of directly using JSTL tags for control flow etc. but remember that FreeMarker has had a rather ergonomic syntax for “foreach” and “if” for years. 

2. Macros. If you want to have reusable template snippets, you can write them as macros and import them. AFAIK, in JSP 2.0 you finally have a sort of macros, but you need to define each snippet in its own file. This is nowhere as elegant as the full namespace/macro solution in FreeMarker. 

3. Transforms. Transforms are the equivalent of body tags in JSP, with a significant distinction that while JSP body tags first cache all of their body and only after that act on them, FreeMarker transforms are fully output-driven, in fact they are implemented internally as chains of java.io.Writer objects. Therefore, regardless of how many transforms you have nested, you can still have progressive page rendering (“can” because a transform can choose to cache all of its body like a JSP body tag, but is not mandated to do so and can provide a clever implementation that allows progressive processing). 

4. Also, the usual argument about usability outside the HTTP protocol stack. If your system does any text output beside HTTP responses – i.e. sends SMTP mail, you can use FreeMarker for generating mail messages from templates, too, or for generating arbitrary XML. It even has declarative XML processing capabilities which make it possible to use it similar to XSLT, but significantly less complex. You can simplify your project by having one language for all your text output generating needs. 

5. Data model flexibility – if you like, you can implement the data model interfaces to naturally represent any underlying data model. I.e. we have a wrapper for Jython objects that pretty faithfully reflects the look and feel of Jython objects in the template syntax. People have reported providing a similar binding for JavaScript etc. 

There’s also lots of goodies like automatic HTML or XML escaping of expressions, convenient literal syntax for lists and maps, etc. 

This much off the top of my head – it’s a bit late here, so I can’t think of anything else at this very moment. 

Velocity's Simplistic design 
Of the three technologies, velocity is the simplest. It has a small amount of very powerful commands. Syntax is as follows. 
Display variable name 

$var 

Display variable name. If null it displays blank 

$!var 

Directives 

#foreach ($item in $collection)  item is $item #end 
#if ($order.total == 0) No charge #end 
#parse("header.vm") 
#macro 
#include("disclaimer.txt") 
#set ($customer = ${order.customer}) 

Code Comparisons 
Here is some code that is written in JSP. This is the logic that would be used when processing a number named "number" is passed in as a parameter. 

<%@ page language="java" %> 
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %> 

<!-- Is the number guess right? --> 
<logic:equal parameter="number" value="7"> 
  You guessed right! You win a high speed blender! 
</logic:equal> 

<!-- If the number guessed was wrong --> 
<logic:notEqual parameter="number" value="7"> 
  <!-- Less Than --> 
  <logic:lessThan parameter="number" value="7"> 
         A little higher... 
  </logic:lessThan> 
  <!-- Greater Than --> 
  <logic:greaterThan parameter="number" value="7"> 
         A little lower... 
  </logic:greaterThan> 
</logic:notEqual> 

And here is the same logic within a velocity template 

<!-- Is the number guess right? --> 
#if ( $number == 7 ) 
  You guessed right! You win a high speed blender! 
#end 

<!-- If the number guessed was wrong --> 
#if ( $number != 7 ) 
    <!-- Less Than --> 
    #if ( $number < 7 ) 
         A little higher... 
    <!-- Greater Than --> 
    #elseif ( $number > 7 ) 
         A little lower... 
    #end 
#end 

Now a another example with the same task. Create a list and display it. First JSP. 

<%@ page language="java" %> 
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> 
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %> 

<% 
java.util.ArrayList list = new java.util.ArrayList(); 
  list.add("First"); 
  list.add("Second"); 
  list.add("Third"); 
  list.add("Fourth"); 
  list.add("Fifth"); 
  pageContext.setAttribute("list", list, PageContext.PAGE_SCOPE); 
%> 

<logic:iterate id="myCollectionElement" name="list"> 
  Element Value: <bean:write name="myCollectionElement" /><br /> 
</logic:iterate> 

And here is the velocity version. 

#set ( $list = ["First", "Second", "Third", "Fourth", "Fifth"] ) 

#foreach ( $item in $list ) 
  Element Value: $item<br /> 
#end 

Conclusion 
JSP has provided developers with a very useful library and toolset. It has been around for a long time and there are no signs that its users are declining. Due to MVC style architecture, server side processing including business logic should not take place within the view component. I did not get into Velocity vs Freemarker debate since they are identical from an architectural standpoint. You can make that decision by comparing the template language itself and choose which is better suited for your needs. When determining which technology to utilize I hope that you take time to research each technology and use this article as a reference. 

猜你喜欢

转载自rongdmmap-126-com.iteye.com/blog/1404092