您的位置:首页 > 编程语言 > Java开发

Spring MVC整合Velocity

2017-03-30 09:43 330 查看


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>

好了显示正常。



源码下载:源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: