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>

好了显示正常。

源码下载:源码

最新文章

  1. JavaScript电子时钟+倒计时
  2. qt-5.6.0 移植之qt源码编译
  3. C#图片处理示例(裁剪,缩放,清晰度,水印)
  4. Qt 之 QQ系统表情(五)
  5. Java自学成长路线(转载)
  6. 【JPA】表达条件查询的关键字
  7. 转载收藏之用 - 微信公众平台开发教程(四):Hello World
  8. HDU 1172 猜数字(DFS)
  9. OpenStack IdentityService Keystone V3 API Curl实战
  10. 中国气象台api
  11. Grunt那些事
  12. HTML+CSS画一朵向日葵
  13. BeanShell Sample与控制台交互
  14. RuntimeException和Exception区别
  15. Echarts学习之路2(基本配置项)
  16. Yocto和Android编译命令的简化和自动完成的实现
  17. python之旅六【第六篇】模块
  18. mybatis cloud not autowired
  19. 机器学习算法中如何选取超参数:学习速率、正则项系数、minibatch size
  20. Linux(CentOS)上配置 SFTP(附解决Write failed: Broken pipe Couldn&#39;t read packet: Connection reset by peer)

热门文章

  1. 分布式数据库hbase详解
  2. 原型模式--prototype
  3. Eclipse中Maven工程缺少Maven Dependencies
  4. Array.prototype.slice.call
  5. Linux下静态库生成和使用
  6. Struts2文件下载
  7. django 命名空间详解
  8. Python字典 (dictionary)
  9. JS、OnClientClick、OnClick
  10. 深入DNS