Spring MVC整合Velocity

Velocity模板(VM)語言介紹

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

Velocity如今應用很是普遍,如今嘗試將SpringMVC項目與Velocity整合。java

整合過程

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

(1)加入dependencygithub

<!-- 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)視圖配置web

<!-- 視圖模式配置,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配置文件spring

#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.vmapache

<!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加入配置spring-mvc

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

好了顯示正常。
mybatis

源碼下載:源碼架構

相關文章
相關標籤/搜索