天天看點

spring mvc中應用velocity

Velocity

Velocity是一款基于java的模闆引擎。相比于jsp而言,它被使用的人可能并不多,但的确也是一款出色的模闆引擎。jsp中允許出現java代碼,而Velocity不允許,也是為了友善維護模闆,嚴格遵從MVC設計原則。模闆隻負責頁面的規劃,渲染頁面。當然Velocity的定位不僅僅在web頁面的開發上使得前後端開發者可以更明确的職責分離,它還可以應用在其它涉及模闆應用的領域,比如代碼生成,SQL生成等等。freemark也是類似于velocity這樣一款模闆引擎。

SpringMvc內建Velocity

在mvc配置檔案中配置velocity引擎,及viewResolver

<bean id="velocityConfig"
	class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
	<property name="resourceLoaderPath" value="/WEB-INF/views/" />
	<property name="configLocation" value="classpath:properties/velocity.properties" />
</bean>
<bean id="viewResolver"
	class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
	<property name="suffix" value=".html" />
	<property name="cache" value="false" />
	<property name="contentType" value="text/html;charset=utf-8" />
	<property name="dateToolAttribute" value="date" /><!--日期函數名稱-->
	<property name="numberToolAttribute" value="number" /><!--數字函數名稱-->
	<property name="layoutUrl" value="layout/default.vm"/>
	<property name="toolboxConfigLocation" value="/WEB-INF/toolbox.xml" />
</bean>
           

velocity.properties

input.encoding=utf-8
output.encoding=utf-8
velocimacro.library=macro/macro.vm
velocimacro.library.autoreload=true
runtime.log.logsystem.class = org.apache.velocity.runtime.log.Log4JLogChute
userdirective=com.baomidou.framework.velocity.directive.BlockDirective,com.baomidou.framework.velocity.directive.OverrideDirective,com.baomidou.framework.velocity.directive.ExtendsDirective
#file.resource.loader.cache = true
           

velocimacro.library配置使用者自定義的宏

userdirective配置使用者自定義的指令

resourceLoaderPath配置velocity的模闆檔案位置

Velocity特色

velocity的核心是模闆引擎、資料上下文,靈活的表達式、控制渲染的指令、宏

通過表達式我們可以取用context資料

通過基本指令set、if、parset、include、foreach等等,我們可以定義變量、子產品化模闆、動态渲染頁面

通過使用自定義指令,我們可以實作一些繼承特性

通過使用宏或者spring内置宏,我們可以靈活複用渲染邏輯、結合mvc對接web Model

關于Velocity,我們需要明白它在web領域主要是應用在後端視圖解析渲染,類似于jsp。在模闆中的js,css,html它并不會幹涉,而涉及vtl的表達式,它會進行渲染。當伺服器把VTL渲染後HTML推送到前端浏覽器時,這時js,css,html才會起作用,浏覽器會運作js,渲染界面,呈現給使用者UI。