Spring MVC整合Velocity
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>
好了显示正常。
源码下载:源码
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?