velocity是類似於jsp並且比jsp更爲強大的引擎,用法也很簡單
和jsp的配置差不多
1.在mvc-servlet.xml中配置velocity的引擎、視圖解析器、配置文件路徑等配置;
2.視圖層使用**.vm格式即可
基本用法可自行百度 這裏說自定義指令的做法
1. 創建一個類繼承自Directive類 (這是velocity定義指令必須使用的類)
2. 實現Directive類裏定義的三個抽象方法,
1.getName()此方法用來設置指令的名稱
2.getType()此方法用來設置是否需要結束語句
3.render(InternalContextAdapter context, Writer writer, Node node) 此方法中寫指令需要執行的內容,其中context 是傳入的參數的內容,writer用來輸出結果,node此對象如果用多個參數使用jjtGetChild(index)來獲取參數位置通過.value(context)獲取當前位置參數的值
3.需要在velocity的配置文件中配置此節點的位置,以便於當前自定義指令的初始化
4. 都完成之後可以在vm文件中 通過配置的getName名稱進行調用 例如 假設指令名稱配置爲name #name(“參數1”,”參數2”);即可!
簡單的代碼如下:
1.mvn-servlet.xml配置
<!--velocity配置-->
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
//配置視圖層的路徑
<property name="resourceLoaderPath" value="/WEB-INF/views"/>
//velocity配置文件的位置
<property name="configLocation" value="classpath:velocity.properties"/>
//字符編碼
<property name="velocityProperties">
<props>
<prop key="input.encoding">utf-8</prop>
<prop key="output.encoding">utf-8</prop>
</props>
</property>
</bean>
<!--配置velocity試圖解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
//解析字符串增加後綴
<property name="suffix" value=".vm"/>
//前綴
<property name="prefix" value=""/>
//返回的類型
<property name="contentType" value="text/html;charset=utf-8"/>
</bean>
自定的directive代碼如下:
public class DemoDirective extends Directive{
@Override
public String getName() {
return "demo";//自定義指令的名稱
}
@Override
public int getType() {
return 2;//配置不帶結束符
}
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
//獲取參數的值
String str1 = node.jjtGetChild(0).value(context).toString();//第一個參數的值
String str2 = node.jjtGetChild(1).value(context).toString();//第二個參數的值
StringBuffer str = new StringBuffer();//創建字符串對象
if(str1 !=null){
str =str.append("<p>測試結果1:"+str1+"</p>");//顯示一段html
}
if(str2 !=null){
str =str.append("<p>測試結果2:"+str2+"</p>");
}
writer.write(str.toString());//輸出結果
return true;
}
}
配置文件配置代碼:
resource.loader = file
file.resource.loader.description = Velocity File Resource Loader
#encoding
input.encoding=UTF-8
output.encoding=UTF-8
#autoreload when vm changed
file.resource.loader.cache=false
file.resource.loader.modificationCheckInterval=2
velocimacro.library.autoreload=false
#自定義指令############################ 配置自定義指令的絕對路徑
userdirective = com.mixa.util.DemoDirective
###########################################
視圖層代碼:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
//測試指令
#demo("參數1","參數2");
</body>
</html>
輸出結果:
測試結果1:參數1
測試結果2:參數2
這是最簡單的一個測試類 大家可以根據需要在render中書寫相應的業務邏輯以獲取到自己想要的htmL對象結果返回到vm顯示
多少不凡、只因不甘!
一個初出茅廬的程序員 希望成長 希望進步