第五章 使用velocity模板引擎
最爽的Web組合開(kāi)發(fā)就是Intellij IDEA + Maven + Spring Boot + Scala + Velocity + Boostrap + jQuery了.
Spring Boot提供了一個(gè)強(qiáng)大的一鍵式Spring的集成開(kāi)發(fā)環(huán)境奠滑,能夠單獨(dú)進(jìn)行一個(gè)Spring應(yīng)用的開(kāi)發(fā),其中:
(1)集中式配置(application.properties)+注解癞己,大大簡(jiǎn)化了開(kāi)發(fā)流程
(2)內(nèi)嵌的Tomcat和Jetty容器,可直接打成jar包啟動(dòng)柱嫌,無(wú)需提供Java war包以及繁瑣的Web配置
(3)提供了Spring各個(gè)插件的基于Maven的pom模板配置妥色,開(kāi)箱即用拆魏,便利無(wú)比气筋。
(4)可以在任何你想自動(dòng)化配置的地方缝驳,實(shí)現(xiàn)可能
(5)提供更多的企業(yè)級(jí)開(kāi)發(fā)特性连锯,如何系統(tǒng)監(jiān)控,健康診斷用狱,權(quán)限控制
(6)無(wú)冗余代碼生成和XML強(qiáng)制配置
(7)提供支持強(qiáng)大的Restfult風(fēng)格的編碼运怖,非常簡(jiǎn)潔
當(dāng)然Spring Boot提供的功能,遠(yuǎn)遠(yuǎn)比上面的強(qiáng)大. Spring boot集成了servlet容器齿拂,當(dāng)我們?cè)趐om文件中增加spring-boot-starter-web的maven依賴時(shí)驳规,不做任何web相關(guān)的配置便能提供web服務(wù),這還得歸于spring boot 自動(dòng)配置的功能(因?yàn)榧恿薊nableAutoConfiguration的注解)署海,幫我們創(chuàng)建了一堆默認(rèn)的配置吗购,以前在web.xml中配置,現(xiàn)在都可以通過(guò)spring bean的方式進(jìn)行配置砸狞,由spring來(lái)進(jìn)行生命周期的管理捻勉,大多數(shù)情況下,我們需要重載這些配置(例如修改服務(wù)的啟動(dòng)端口刀森,contextpath,filter,listener,servlet,session超時(shí)時(shí)間等)
本章我們介紹一下,在SB中使用模板引擎Velocity.
SB默認(rèn)支持的模板引擎
spring boot會(huì)自動(dòng)配置 FreeMarker,Thymeleaf,Velocity踱启,只需要在pom中加入相應(yīng)的依賴即可
SB使用Velocity的依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-velocity</artifactId>
</dependency>
默認(rèn)配置下spring boot會(huì)從src/main/resources/templates目錄中去找模板
SB的velocity配置
application.properties配置
lightsword/src/main/resources/application.properties
# VELOCITY TEMPLATES (VelocityAutoConfiguration)
spring.velocity.charset=UTF-8
spring.velocity.properties.input.encoding=UTF-8
spring.velocity.properties.output.encoding=UTF-8
spring.velocity.resourceLoaderPath=classpath:/templates/
spring.velocity.suffix=.html
spring.velocity.toolbox-config-location=/WEB-INF/toolbox.xml
這樣,SB會(huì)從src/main/resources/templates目錄中去找以.html后綴的模板文件.
Controller里面的Model
數(shù)據(jù)httpapis通過(guò)model傳到模板文件(SpringMVC框架里面做的事情):
model.addAttribute("httpapis", HttpApiDao.findAll())
完整的Controller代碼:
package com.springboot.in.action.controller
import java.util.Date
import java.util.concurrent.CountDownLatch
import com.alibaba.fastjson.JSON
import com.springboot.in.action.dao.{HttpApiDao, HttpReportDao, HttpSuiteDao}
import com.springboot.in.action.engine.OkHttp
import com.springboot.in.action.entity.{HttpApi, HttpReport}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.{PathVariable, RequestMapping, RequestMethod, RequestParam, ResponseBody, RestController}
import org.springframework.web.servlet.ModelAndView
import scala.collection.JavaConversions._
@RestController
@RequestMapping(Array("/httpapi"))
class HttpApiController @Autowired() (
val HttpSuiteDao: HttpSuiteDao,
val HttpApiDao: HttpApiDao,
val HttpReportDao: HttpReportDao) {
@RequestMapping(value = {
Array("", "/")
}, method = Array(RequestMethod.GET))
def list(model: Model) = {
model.addAttribute("httpapis", HttpApiDao.findAll())
new ModelAndView("/httpapi/list")
}
...
}
模板文件list.html
lightsword/src/main/resources/templates/httpapi/list.html
#include("/common/header.html")
<div class="form-group">
<table style="word-break: break-all; word-wrap: break-all;"
class="table table-hover table-condensed table-responsive">
<thead>
<tr>
<th style='width: 60px'>Id</th>
<th style='width: 100px'>用例名稱</th>
<th>URL</th>
<th style='width: 80px'>方法</th>
<th style='width: 100px'>期望輸出</th>
<th style='width: 60px'>次數(shù)</th>
<th>狀態(tài)</th>
<th style='width: 90px'>創(chuàng)建人</th>
<th style='width: 120px'>調(diào)用時(shí)間</th>
<th style='width: 60px'>操作</th>
<th>執(zhí)行測(cè)試</th>
</tr>
</thead>
<tbody>
#foreach ($t in $httpapis)
<tr>
<td>$!t.id</td>
<td>$!t.name</td>
<td>$!t.url</td>
<td>$!t.method</td>
<td>$!t.expectOutput</td>
<td>$!t.runTimes</td> #if($!t.state==1)
<td><div class="btn btn-success">成功</div></td> #elseif($!t.state==0)
<td><div class="btn btn-danger">失敗</div></td> #else
<td><div class="btn btn-info">未執(zhí)行</div></td> #end
<td>$!t.owner</td>
<td>$!DateTool.format('yyyy-MM-dd HH:mm:ss', $!t.gmtModify)</td>
<td><a href="/httpapi/detailPage/$t.id">查看</a></td>
<td><div id='btn-$t.id' class='btn btn-primary'
onclick='runTest($t.id)'>運(yùn)行</div></td>
</tr>
#end
</tbody>
</table>
</div>
<script>
function runTest(id) {
var url = '/httpapi/runTest?id=' + id
$.getJSON(url, function(data) {
if (data) {
alert('響應(yīng)結(jié)果:' + JSON.stringify(data, null, 2))
location.reload()
} else {
alert('執(zhí)行失敗')
}
})
}
</script>
#include("/common/footer.html")
velocity的語(yǔ)法詳情參考:
toolbox的使用
我們?cè)趘elocity模板文件中有時(shí)候需要格式化小數(shù)點(diǎn),日期等輸出,我們可以使用toolbox.
我們看到application.properties有這么一行配置:
spring.velocity.toolbox-config-location=/WEB-INF/toolbox.xml
然后,在list.html里面有這么一行代碼
<td>$!DateTool.format('yyyy-MM-dd HH:mm:ss', $!t.gmtModify)</td>
這個(gè)DateTool就是我們這里要說(shuō)的toolbox的功能.
lightsword/src/main/resources/WEB-INF/toolbox.xml的配置如下
<?xml version="1.0" encoding="UTF-8"?>
<!-- ============================================================= @(#) toolbox.xml
Copyright (c) 2016, Project, All Rights Reserved. ============================================================= -->
<toolbox>
<!-- [ DateTool ] @see http://www.jajakarta.org/velocity/tools/velocity-tools-1.1/docs-ja/generic/DateTool.html
(ja) @see http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/DateTool.html
(en) @since VelocityTools 1.0 -->
<tool>
<key>DateTool</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.DateTool</class>
</tool>
<!-- [ MathTool ] @see http://www.jajakarta.org/velocity/tools/velocity-tools-1.1/docs-ja/generic/MathTool.html
(ja) @see http://velocity.apache.org/tools/devel/generic/MathTool.html (en)
@since VelocityTools 1.0 -->
<tool>
<key>MathTool</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.MathTool</class>
</tool>
<!-- [ NumberTool ] @see http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/NumberTool.html
(en) @since VelocityTools 1.2 -->
<tool>
<key>NumberTool</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.NumberTool</class>
</tool>
<!-- [ RenderTool ] @see http://velocity.apache.org/tools/devel/generic/RenderTool.html
(en) @since VelocityTools 1.0 <tool> <key>render</key> <scope>application</scope>
<class>org.apache.velocity.tools.generic.RenderTool</class> </tool> -->
<!-- [ EscapeTool ] @see http://velocity.apache.org/tools/devel/generic/EscapeTool.html
(en) @since VelocityTools 1.2 -->
<tool>
<key>EscapeTool</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.EscapeTool</class>
</tool>
<!-- [ ResourceTool ] @see http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/ResourceTool.html
(en) @since Velocity 1.3 <tool> <key>text</key> <class>org.apache.velocity.tools.generic.ResourceTool</class>
<parameter name="bundles" value="resources,prj.hoboken.patrasche.resources.PatrascheResources"
/> <parameter name="locale" value="ja_JP" /> </tool> -->
<!-- [ AlternatorTool ] @see http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/AlternatorTool.html
(en) @since VelocityTools 1.2 -->
<tool>
<key>AlternatorTool</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.AlternatorTool</class>
</tool>
<!-- [ ValueParser ] @see http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/ValueParser.html
(en) @since VelocityTools 1.2 -->
<tool>
<key>ValueParser</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.ValueParser</class>
</tool>
<!-- [ ListTool ] @see http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/ListTool.html
(en) @since VelocityTools 1.2 -->
<tool>
<key>ListTool</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.ListTool</class>
</tool>
<!-- [ SortTool ] @see http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/SortTool.html
(en) @since VelocityTools 1.2 -->
<tool>
<key>SortTool</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.SortTool</class>
</tool>
<!-- [ IteratorTool ] @see http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/IteratorTool.html
(en) @since VelocityTools 1.0 -->
<tool>
<key>IteratorTool</key>
<scope>request</scope>
<class>org.apache.velocity.tools.generic.IteratorTool</class>
</tool>
<!-- ============================================================ [ TOOL
FOR STRUTS TAGLIB ] ============================================================ -->
<!-- [ ActionMessagesTool ] @see http://www.jajakarta.org/velocity/tools/velocity-tools-1.1/docs-ja/struts/ActionMessagesTool.html
(ja) @see http://velocity.apache.org/tools/devel/struts/ActionMessagesTool.html
(en) @since VelocityTools 1.1 -->
<tool>
<key>ActionMessagesTool</key>
<scope>request</scope>
<class>org.apache.velocity.tools.struts.ActionMessagesTool</class>
</tool>
<!-- [ ErrorsTool ] @see http://www.jajakarta.org/velocity/tools/velocity-tools-1.1/docs-ja/struts/ErrorsTool.html
(ja) @see http://velocity.apache.org/tools/devel/struts/ErrorsTool.html (en)
@since VelocityTools 1.0 -->
<tool>
<key>ErrorsTool</key>
<scope>request</scope>
<class>org.apache.velocity.tools.struts.ErrorsTool</class>
</tool>
<!-- [ FormTool ] @see http://www.jajakarta.org/velocity/tools/velocity-tools-1.1/docs-ja/struts/FormTool.html
(ja) @see http://velocity.apache.org/tools/devel/struts/FormTool.html (en)
@since VelocityTools 1.0 -->
<tool>
<key>FormTool</key>
<scope>request</scope>
<class>org.apache.velocity.tools.struts.FormTool</class>
</tool>
<!-- [ MessageTool ] @see http://www.jajakarta.org/velocity/tools/velocity-tools-1.1/docs-ja/struts/MessageTool.html
(ja) @see http://velocity.apache.org/tools/devel/struts/MessageTool.html
(en) @since VelocityTools 1.0 -->
<tool>
<key>MessageTool</key>
<scope>request</scope>
<class>org.apache.velocity.tools.struts.MessageTool</class>
</tool>
<!-- [ StrutsLinkTool ] LinkTool @see http://www.jajakarta.org/velocity/tools/velocity-tools-1.1/docs-ja/struts/StrutsLinkTool.html
(ja) @see http://velocity.apache.org/tools/devel/struts/StrutsLinkTool.html
(en) @since VelocityTools 1.0 -->
<tool>
<key>StrutsLinkTool</key>
<scope>request</scope>
<class>org.apache.velocity.tools.struts.StrutsLinkTool</class>
</tool>
<!-- [ SecureLinkTool ] LinkTool @see http://www.jajakarta.org/velocity/tools/velocity-tools-1.1/docs-ja/struts/SecureLinkTool.html
(ja) @see http://velocity.apache.org/tools/devel/struts/SecureLinkTool.html
(en) @since VelocityTools 1.1 -->
<tool>
<key>SecureLinkTool</key>
<scope>request</scope>
<class>org.apache.velocity.tools.struts.SecureLinkTool</class>
</tool>
<!-- [ TilesTool ] Tiles @see http://www.jajakarta.org/velocity/tools/velocity-tools-1.1/docs-ja/struts/TilesTool.html
(ja) @see http://velocity.apache.org/tools/devel/struts/TilesTool.html (en)
@since VelocityTools 1.1 -->
<tool>
<key>TilesTool</key>
<scope>request</scope>
<class>org.apache.velocity.tools.struts.TilesTool</class>
</tool>
<!-- [ ValidatorTool ] Validator @see http://www.jajakarta.org/velocity/tools/velocity-tools-1.1/docs-ja/struts/ValidatorTool.html
(ja) @see http://velocity.apache.org/tools/devel/struts/ValidatorTool.html
(en) @since VelocityTools 1.1 -->
<tool>
<key>ValidatorTool</key>
<scope>request</scope>
<class>org.apache.velocity.tools.struts.ValidatorTool</class>
</tool>
</toolbox>
這樣我們就可以在模板文件中使用類似DateTool這樣的工具類了.同時(shí)我們也可以在代碼里自己實(shí)現(xiàn)工具類,然后配置到toolbox.xml文件里.