freemarker做爲視圖技術出現的比velocity早,想當年struts風靡一時,freemarker做爲視圖層也風光了一把。但如今velocity做爲後起之秀的輕量級模板引擎,更容易獲得青睞。這裏不討論velocity,有興趣的同窗能夠看下。freemarker雖然比velocity重,但它確實功能強大,好比日期、貨幣格式化提供了不少轉換方法,還一個特點招牌菜就是宏指令,它能夠像java裏的方法調用同樣在頁面玩轉視圖處理。html
這裏主要演示下怎麼在當今最流行的spring mvc中集成freemarker。首先咱們仍是引入jar,先在maven的pom文件中加入:java
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
接下來是在spring mvc的配置文件spring-mvc.xml中引入freemark的相關配置web
<!--配置freemarker視圖解析器 -->
<bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/" />
</bean>spring
<bean id="ViewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="suffix" value=".html" />
<property name="contentType" value="text/html; charset=UTF-8" />
</bean>spring-mvc
最後修改html文件,把原來velocity的變量名外面再套一個大括號就能夠了,固然其餘語法格式也須要相應修改,如循環要由foreach改成list:tomcat
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>測試樁配置頁面</title> </head> <body> <form id="interfaceForm"> <h2 align="center"> <font color="#FF0000">測試樁配置</font> </h2> <table style="width: 1200px; height: 600px; margin-left: 5%; margin-top: 30px;" border="2px" bordercolor="gray" cellspacing="0px" cellpadding="5px"> <tr height="10%"> <td rowspan="3" width="32%" valign="top" align="center"><font size="4pt" color="black">接口名稱:</font><br /> <br /> <div name="interfaceNames" id="interfaceNames" style="border: solid 2px pink; width: 350px; height: 520px; overflow: auto;"> <!-- <table> #foreach($method in $methodKeys) <tr valign="top" style="height: 25px;"> <td align="center" width="150px"><a onclick="getMethodContent('$method');">$method</a></td> <td width="100px" align="left"><a style="text-decoration: none;" onclick="deleteInterfaceEntity('$method');"> 刪除</a></td> </tr> #end </table> --> <table> <#list methodKeys as method> <tr valign="top" style="height: 25px;"> <td align="center" width="150px"><a onclick="getMethodContent('${method}');">${method}</a></td> <td width="100px" align="left"><a style="text-decoration: none;" onclick="deleteInterfaceEntity('${method}');"> 刪除</a></td> </tr> </#list> </table> </div></td> <td>接口名: <input type="text" name="interfaceName" id="interfaceName" style="width: 400px" /> <input type="button" value="新增/修改" onclick="generateInterfaceEntity();" /></td> </tr> <tr> <td><font size="4pt" color="black"> 接口報文:</font><br /> <br /> <textarea name="interfaceBody" id="interfaceBody" style="width: 700px; height: 450px; margin-left: 50px;"> </textarea></td> </tr> </table> </form> </body>
啓動tomcat,頁面的功能展現跟原來是同樣的。velocity的集成點擊這裏spring mvc集成velocity使用,能夠比對着看velocity和freemarker的集成,你會發現二者相差無幾。其實若是你的項目二者都用到了,是能夠同時集成的。mvc