1. 程式人生 > >Spring MVC 整合Velocity及用法說明

Spring MVC 整合Velocity及用法說明

Velocity是一個基於java的模板引擎(template engine),它允許任何人僅僅簡單的使用模板語言(template language)來引用由java程式碼定義的物件。

配置:

1.在pom.xml增加依賴的velocity包

<dependency>
	<groupId>velocity</groupId>
	<artifactId>velocity</artifactId>
	<version>1.5</version>
</dependency>

2.在servlet-context.xml中增加以下內容,如果有jsp的配置先註釋掉
<beans:bean id="velocityConfig"
class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
	<beans:property name="resourceLoaderPath" value="/WEB-INF/views" />
	<beans:property name="configLocation" value="classpath:common/velocity.properties" />
</beans:bean>

<beans:bean id="velocityViewResolver"
	class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
	<beans:property name="suffix" value=".htm" />
</beans:bean>

3.在resources/common目錄下建立velocity.properties

#encoding
input.encoding  =UTF-8
output.encoding=UTF-8
contentType=text/html;charset=UTF-8

#autoreload when vm changed
file.resource.loader.cache=false
file.resource.loader.modificationCheckInterval  =1
velocimacro.library.autoreload=false

4.新建testController
@RequestMapping(value="/test")
@Controller
public class TestController {
	@RequestMapping(value="/index")
	public String index(Model model) {
		String name = "tester";
		model.addAttribute("name", name);
		return "test/index";
	}
}

5.新建test/index.htm模板

<html>
<head>
</head>
<body>
hello $name!
</body>
</html>

6.訪問http://localhost/test/index

顯示 hello tester!

---------------------------------------------------------------------------------------------------------------------------------------------------------------

Velocity的基本語法:

1、"#"用來標識Velocity的指令碼語句,包括#set、#if 、#else、#end、#foreach、#end、#iinclude、#parse、#macro等;
如:
#if($info.imgs)
<img src="$info.imgs" border=0>
#else
<img src="noPhoto.jpg">
#end


2、"$"用來標識一個物件(或理解為變數);如
如:$i、$msg、$TagUtil.options(...)等。


3、"{}"用來明確標識Velocity變數;
比如在頁面中,頁面中有一個$someonename,此時,Velocity將把someonename作為變數名,若我們程式是想在someone這 個變數的後面緊接著顯示name字元,則上面的標籤應該改成${someone}name。


4、"!"用來強制把不存在的變數顯示為空白。
如當頁面中包含$msg,如果msg物件有值,將顯示msg的值,如果不存在msg物件同,則在頁面中將顯示$msg字元。這是我們不希望的,為了把不存 在的變數或變數值為null的物件顯示為空白,則只需要在變數名前加一個“!”號即可。
如:$!msg

5、循#foreach( $info in $list) $info.someList #end,環讀取集合list中的物件

#foreach( $info in $hotL包含檔案#inclue("模板檔名")或#parse("模板檔名")st1) 
<a href="/blog/list?&cid=$!info.cid" target="_blank">$!info.title</a><br>
#end 
上面的指令碼表示迴圈遍歷hotList1集合中的物件,並輸出物件的相關內容。

6、包含檔案#inclue("模板檔名")或#parse("模板檔名")

主要用於處理具有相同內容的頁面,比如每個網站的頂部或尾部內容。
使用方法,可以參考EasyJF開源Blog及EasyJF開源論壇中的應用!
如:#parse("/blog/top.html")或#include("/blog/top.html")
parse與include的區別在於,若包含的檔案中有Velocity指令碼標籤,將會進一步解析,而include將原樣顯示。