1. 程式人生 > >Spring MVC整合Velocity

Spring MVC整合Velocity

java程序 界面設計 配置文件 web開發 engine

Velocity模板(VM)語言介紹

Velocity是一個基於java的模板引擎(template engine)。它允許任何人僅僅簡單的使用模板語言(template language)來引用由java代碼定義的對象。
當Velocity應用於web開發時,界面設計人員可以和java程序開發人員同步開發一個遵循MVC架構的web站點,也就是說,頁面設計人 員可以只關註頁面的顯示效果,而由java程序開發人員關註業務邏輯編碼。Velocity將java代碼從web頁面中分離出來,這樣為web站點的長 期維護提供了便利,同時也為我們在JSP和PHP之外又提供了一種可選的方案。

Velocity現在應用非常廣泛,現在嘗試將SpringMVC項目與Velocity整合。

整合過程

采用以前整合的[SpringMVC項目]。
主要涉及改變的文件:
pom.xml(引入velocity的jar包)
spring-mvc.xml(視圖配置,配置velocity)
velocity.properties(velocity配置文件)

(1)加入dependency

<!-- Velocity模板 -->  
<dependency>  
    <groupId>org.apache.velocity</groupId>  
    <artifactId>velocity</artifactId>  
    <version>1.5</version>  
</dependency>  
<dependency>  
    <groupId>velocity-tools</groupId>  
    <artifactId>velocity-tools-generic</artifactId>  
    <version>1.2</version>  
</dependency>

(2)視圖配置

<!-- 視圖模式配置,velocity配置文件-->
<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="velocityViewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">  
    <property name="suffix" value=".vm" />  
</bean>

(3)velocity.properties配置文件

#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

配置完後,寫一個vm頁面展示所有用戶的userName和age。
showAllUser.vm

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>show all users</title>
</head>
<body>
    <table >
        #foreach($user in $userList)
            <tr >
                <td >$user.userName</td>
                <td >$user.age</td>
            </tr>
        #end
    </table>
</body>
</html>

訪問127.0.0.1/spring_mybatis_springmvc/user/showAllUser.do
可以顯示,但是中文出現了亂碼。
只需在velocityViewResolver加入配置

<property name="contentType"><value>text/html;charset=UTF-8</value></property>

好了顯示正常。
技術分享


Spring MVC整合Velocity