让 Spring3 支持 velocity tools 2.x

本文详细介绍了如何在Spring3中适配Velocitytools2.x版本,包括重写createVelocityContext()方法以加载新的ToolManager,指定VelocityLayoutViewResolver的viewClass属性为自定义类,并配置toolboxConfigLocation来使用Velocitytools2.x的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目前Spring3的 Velocity toolbox 还只是支持到 1.x 版本的,无法使用 velocity tools 2.x 的功能,因此需要进行稍微的改造进而支持 velocity tools 2.x。

1. 使用 velocity tools 2.x 的ToolManager重写createVelocityContext() 方法,以加载tools 2.x:

/**
 * Spring3默认的 createVelocityContext 方法中采用的是 tools-1.x 的 ToolboxManager, ServletToolboxManager等类
 * 加载toolbox,但是 tools 2.x 中已经废弃了这些类,导致了无法加载tools 2.x。
 * 所以,这里采用tools 2.x中新的 ToolManager方式重写此方法加载toolbox2.x。
 */
public class VelocityLayoutToolboxView extends VelocityLayoutView 
{
	@Override
	protected Context createVelocityContext(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		ViewToolContext ctx = new ViewToolContext(this.getVelocityEngine(), request, response, this.getServletContext());
		
		if(this.getToolboxConfigLocation() != null)
		{
			ToolManager tm = new ToolManager();
			tm.setVelocityEngine(this.getVelocityEngine());
			tm.configure(this.getServletContext().getRealPath(this.getToolboxConfigLocation()));
			
			for(String scope : Scope.values())
			{
				ctx.addToolbox(tm.getToolboxFactory().createToolbox(scope));
			}
		}
		
		if(model != null && !mode.isEmpty())
		{
			ctx.putAll(model);
		}
		
		return ctx;
	}
}


2. 指定 VelocityLayoutViewResolver 的 viewClass 属性为自己扩展的类:VelocityLayoutToolboxView
<bean class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResoler">
	<property name="..." value="..."/>
	<property name="viewClass" value="com.my.VelocityLayoutToolboxView"/>
	<property name="toolboxConfigLocation" value="/WEB-INF/tools.xml"/>
</bean>


3. 就可以使用 velocity tools 2.x 的功能了。

转载于:https://my.oschina.net/jsan/blog/202956

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值