目前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;
}
}
<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 的功能了。