pom.xml所需velocity的jar
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>
servlet-context.xml中添加如下配置:
<beans:bean id="velocityConfig"
class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<beans:property name="resourceLoaderPath" value="WEB-INF/views/" /><!-- 模板加载路径 -->
<beans:property name="configLocation"
value="classpath:config/velocity.properties" /><!-- 配置文件 -->
</beans:bean>
<beans:bean id="viewResolver"
class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<beans:property name="suffix" value=".html" /><!-- 后缀 -->
<beans:property name="cache" value="false" /><!-- 模板缓存 -->
<beans:property name="contentType" value="text/html;charset=UTF-8" />
<beans:property name="dateToolAttribute" value="date" /><!-- 日期处理函数名称 -->
<beans:property name="numberToolAttribute" value="number" /><!-- 数字处理函数名称 -->
</beans:bean>
备注:把常用的JSP配置改成Velocity配置
velocity.properties如下配置:
#encoding
input.encoding=UTF-8
output.encoding=UTF-8
contentType=text/html;charset=UTF-8
#autoreload when changed
file.resource.loader.cache=false
file.resource.loader.modificationCheckInterval =1
velocimacro.library.autoreload=false
#These foreach config
directive.foreach.counter.name = velocityCount
directive.foreach.counter.initial.value = 1
directive.foreach.maxloops =-1
java代码
@RequestMapping("getUser")
public String get(HttpServletRequest request, HttpServletResponse response,
Model model) {
logger.info("进入用户查询测试方法!");
String str = request.getParameter("id");
Integer id = new Integer(str);
if (id != null && !id.equals("")) {
User user = userService.getUser(id);
model.addAttribute("user", user);
}
return "home/index";
}
Velocity的使用
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div>hello $!{user.name}!</div>
<div>CreateDate $!date.format('yyyy-MM-dd HH:mm:ss ',${user.createdDate})</div>
<div>Price $!number.format("#0.00", ${price})</div></span>
</body>
</html>
VelocityLayoutViewResolver配置方法
别人以写好了,我就不在做搬运工了!
Spring MVC中配置使用org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver请参考