关于Java中如何使用velocity

      最近做项目,遇到后台Date时间类型传到前台显示为英文问题,本来是自己在结果前先将Date类型时间处理成String类型传至前台,后来觉得麻烦,发现可以使用Velocity直接前台调用java类方法进行类型转换。

      我们先了解一下什么事velocity。velocity是一种基于java的模板引擎技术,有点类似与JSP,它允许页面设计者引用Java中定义的方法。前端页面设计者和后端Java开发者能够同时使用MVC的模式开发网站,这样前端能够把精力放在页面的设计上,后端也可以把精力放在代码开发上。Velocity把Java代码从Web页面中分离, 使网站可维护性更强。

      那么我们应该如何在项目中配置velocity呢?(注:我这里项目用的是SSM+Maven)

  1. 添加velocity依赖的jar包,这里使用maven管理依赖,所以只需要在pom.xml中添加:
			<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.配置注意这里的contextConfigLocation参数,它指向了classpath路径下的spring目录下的zshop_servlet.xml文件,这里就是我们的spring的配置文件,我们将在这里配置Velocity的bean.

 <!-- 
配置VelocityConfigurer,负责在spring中设置Velocity引擎。通过属性resourceLoaderPath告诉Velocity到哪里寻找它的模板。
通常将模板放到WEB-INF下的某个子目录下,可以保证这些模板不能被直接访问。
-->

<bean class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
	    <property name="cache" value="true" />
		<property name="exposeSpringMacroHelpers" value="true" />
		<property name="requestContextAttribute" value="rc" />
		<property name="exposeSessionAttributes" value="true" />
		<property name="order" value="1" />
		<property name="contentType" value="text/html; charset=UTF-8" />
		<property name="viewClass" value="org.springframework.web.servlet.view.velocity.VelocityView" />
		<property name="allowSessionOverride" value="true"/>
		<property name="toolboxConfigLocation" value="/WEB-INF/config/velocity-toolbox.xml" />
	</bean>
<!--配置试图解析器-->
	<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
   		<property name="resourceLoaderPath" value="/WEB-INF/views/" />
   		<property name="velocityProperties">
			<props>
				<prop key="input.encoding">UTF-8</prop>
				<prop key="output.encoding">UTF-8</prop>
				<prop key="parser.pool.size">100</prop>
				<prop key="velocimacro.library.autoreload">true</prop>
			</props>
		</property>
    </bean>

在上面配置中,我们配置了一个velocity-toolbox.xml,那么我们在对应的路径下新建一个velocity-toolbox.xml,做出如下配置:

<?xml version="1.0"?>
<toolbox>
	<tool>
		<key>dateUtil</key>
		<scope>application</scope>
		<class>com.zxtg.zshop.util.DateUtil</class>
	</tool>
	
	<tool>
		<key>moneyUtil</key>
		<scope>application</scope>
		<class>com.zxtg.zshop.util.MoneyUtil</class>
	</tool>
	
	<tool>
		<key>commonUtil</key>
		<scope>application</scope>
		<class>com.zxtg.zshop.util.CommonUtil</class>
	</tool>
</toolbox>

这个配置文件可以让我们在vm中使用后台java类中定义的方法!

完成以上使用velocity的流程后,我们可以在"/WEB-INF/velocity/templates"下新建一些.vm的文件用于展示数据,

案例代码:

<td>$!{moneyUtil.getFormatAmount($!{info.couponValue})}</td>
<td>$!{dateUtil.simpleDateFormatChinese($!{info.acceptTime})}</td>
<td>$!{dateUtil.simpleDateFormatmdhChinese($!{info.beginTime})}</td>

另附Java工具类DateUtil.java代码:

package com.zxtg.zshop.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class DateUtil {

	/** 完整时间 yyyy-MM-dd HH:00:00 */
	public static final String dtSimpleYmdh = "yyyy-MM-dd HH:00:00";

	public static final String dtSimpleYmdhms = "yyyy-MM-dd HH:mm:ss";


	private static SimpleDateFormat format = new SimpleDateFormat(
			dtSimpleYmdhms);

	
	
	public static final String simpleFormatYmdhms(Date date) {
		if (date == null) {
			return "";
		}
		return getFormat(dtSimpleYmdhms).format(date);
	}

	public static final String simpleFormatYmdhm(Date date) {
		if (date == null) {
			return "";
		}
		return getFormat(dtSimpleYmdhm).format(date);
	}

	public static final String simpleFormatMdhm(Date date) {
		if (date == null) {
			return "";
		}
		return getFormat(dtSimpleMdhm).format(date);
	}

	/**
	 * HH:mm
	 */

	public static final String simpleFormathm(Date date) {
		if (date == null) {
			return "";
		}
		return getFormat(simplehm).format(date);
	}

	/**
	 * yyyy-MM-dd
	 * 
	 * @param date
	 * @return
	 */
	public static final String simpleFormat(Date date) {
		if (date == null) {
			return "";
		}
		return getFormat(dtSimple).format(date);
	}

	public static final String simpleFormatMD(Date date) {
		if (date == null) {
			return "";
		}
		return getFormat(dSimple).format(date);
	}
	
}

另外在2步骤中配置了

<property name="velocityProperties">
	<props>
		<prop key="input.encoding">UTF-8</prop>
		<prop key="output.encoding">UTF-8</prop>
		<prop key="parser.pool.size">100</prop>
		<prop key="velocimacro.library.autoreload">true</prop>
	</props>
</property>
可以使用配置文件替代:
<property name="configLocation" value="classpath:velocity/velocity.properties"/>

新建配置文件velocity.properties:

#模板编码:
input.encoding=UTF-8 //模板输入编码
output.encoding=UTF-8 //模板输出编码
 
#foreach配置
directive.foreach.counter.name = velocityCount //计数器名称
directive.foreach.counter.initial.value = 1 //计数器初始值
directive.foreach.maxloops = -1 //最大循环次数,-1为默认不限制 directive.foreach.iterator.name = velocityHasNex //迭代器名称
 
#set配置
directive.set.null.allowed = false //是否可设置空值
 
#include配置
directive.include.output.errormsg.start = <!-- include error : //错误信息提示开始字符串
directive.include.output.errormsg.end = see error log --> //错误信息提示结束字符串
 
#parse配置
directive.parse.max.depth = 10 //解析深度
 
模板加载器配置
resource.loader = file //模板加载器类型,默认为文件,可定义多个
file.resource.loader.description = Velocity File Resource Loader //加载器描述
file.resource.loader.class = Velocity.Runtime.Resource.Loader.FileResourceLoader //加载器类名称
file.resource.loader.path = . //模板路径
file.resource.loader.cache = false //是否启用模板缓存
file.resource.loader.modificationCheckInterval = 2 //检查模板更改时间间隔
 
宏配置
velocimacro.permissions.allow.inline = true //是否可以行内定义
velocimacro.permissions.allow.inline.to.replace.global = false //是否可以用行内定义代替全局定义
velocimacro.permissions.allow.inline.local.scope = false //行内定义是否只用于局部
velocimacro.context.localscope = false //宏上下文是否只用于局部
velocimacro.max.depth = 20 //解析深度
velocimacro.arguments.strict = false //宏参数是否启用严格模式
 
资源管理器配置
resource.manager.class = Velocity.Runtime.Resource.ResourceManagerImpl //管理器类名称
resource.manager.cache.class = Velocity.Runtime.Resource.ResourceCacheImpl //缓存器类名称
 
解析器池配置
parser.pool.class = Velocity.Runtime.ParserPoolImpl //解析池类名称
parser.pool.size = 40 //初始大小
 
#evaluate配置
directive.evaluate.context.class = Velocity.VelocityContext //上下问类名称
 
可插入introspector配置
runtime.introspector.uberspect = Velocity.Util.Introspection.UberspectImpl //默认introspector类名称
--------------------- 

原文:https://blog.csdn.net/zengdeqing2012/article/details/51140239 

--------------------------------------------------来自不正经的程序袁 For the Peace and Love-------------------------------------------------

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值