freemarker作為視圖技術出現的比velocity早,想當年struts風靡一時,freemarker作為視圖層也風光了一把。但現在velocity作為后起之秀的輕量級模板引擎,更容易得到青睞。這里不討論velocity,有興趣的同學可以看下。freemarker雖然比velocity重,但它確實功能強大,比如日期、貨幣格式化提供了很多轉換方法,還一個特色招牌菜就是宏指令,它可以像java里的方法調用一樣在頁面玩轉視圖處理。
這里主要演示下怎么在當今最流行的spring mvc中集成freemarker。首先我們還是引入jar,先在maven的pom文件中加入:
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
接下來是在spring mvc的配置文件spring-mvc.xml中引入freemark的相關配置
<!--配置freemarker視圖解析器 -->
<bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/" />
</bean>
<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>
最后修改html文件,把原來velocity的變量名外面再套一個大括號就可以了,當然其他語法格式也需要相應修改,如循環要由foreach改為list:
<!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的集成,你會發現兩者相差無幾。其實如果你的項目兩者都用到了,是可以同時集成的。