Velocity配置应用
1. 加入jar包
在pom.xml中选择Dependencies进行添加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>
2.application.properties文件
设置vm文件存放目录;
velocityUrl=D:\\velocity(文件夹),将vm文件放入此文件中。
3. applictionContext.xml文件
<util:propertiesid="applicationProps"location="classpath:application.properties"/>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"value="classpath:application.properties" />
</bean>
<beanid="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<propertyname="velocityProperties">
<props>
<propkey="input.encoding">GBK</prop>
<propkey="file.resource.loader.path">${velocityurl}</prop>
</props>
</property>
</bean>
4. 在类文件里写入代码,查询并将值返回到vm模板,以jsp形式展示。
1) VelocityEngine类:VelocityEngine是Velocity的核心,可以从Apache上下载。利用VelocityEngine解析事先定义好的vm模板,并将结果发送到客户端即可。
@Autowired
privateVelocityEngine velocityEngine;
@RequestMapping(value="",method= RequestMethod.POST)
publicString information(HttpServletRequest request){
//实例化一个VelocityContext
VelocityContext context=newVelocityContext();
//获取数据集合
List<Map<String,Object>> list =service.queryKsxxList(1);
//向VelocityContext中放入键值
context.put("ds",list);
//实例化一个StringWriter
StringWriterwriter=new StringWriter();
//从vm目录下加载vm模板
velocityEngine.mergeTemplate("/ksxx.vm","gbk", context, writer); //写入模板
request.setAttribute("velocityStr",writer.toString());
return"ksxx"; //返回jsp
}
5. sp页面取值
${velocityStr}
6. vm模板取值
<td>姓名</td>
<td>$!ds[0].ksxm</td>
循环:
#foreach($elem in $!cy)
<tr>
<td>$!elem.cw</td>
<td>$!elem.xm</td>
<td>$!elem.nn</td>
</tr>
#end