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

源码下载:源码架构

相关文章
相关标签/搜索