标签:
使用velocity后,原来的很多标签无法使用了,必须借助velocity tools来完成,目前velocity tools最新版本是2.0,下面是velocity tools的一些注意事项:
1. 与Spring MVC 3.x/4.x的集成问题
Spring 3.x/4.x只支持1.3.x的velocity tools,要使用2.0必须自己扩展VelocityToolboxView类
1 package org.springframework.web.servlet.view.velocity; 2 3 import java.util.Map; 4 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 8 import org.apache.velocity.context.Context; 9 import org.apache.velocity.tools.Scope; 10 import org.apache.velocity.tools.ToolManager; 11 import org.apache.velocity.tools.view.ViewToolContext; 12 import org.springframework.web.servlet.view.velocity.VelocityToolboxView; 13 14 public class VelocityToolbox2View extends VelocityToolboxView { 15 @Override 16 protected Context createVelocityContext(Map<String, Object> model, 17 HttpServletRequest request, HttpServletResponse response) 18 throws Exception {// Create a 19 // ChainedContext 20 // instance. 21 ViewToolContext ctx; 22 23 ctx = new ViewToolContext(getVelocityEngine(), request, response, 24 getServletContext()); 25 26 ctx.putAll(model); 27 28 if (this.getToolboxConfigLocation() != null) { 29 ToolManager tm = new ToolManager(); 30 tm.setVelocityEngine(getVelocityEngine()); 31 tm.configure(getServletContext().getRealPath( 32 getToolboxConfigLocation())); 33 if (tm.getToolboxFactory().hasTools(Scope.REQUEST)) { 34 ctx.addToolbox(tm.getToolboxFactory().createToolbox( 35 Scope.REQUEST)); 36 } 37 if (tm.getToolboxFactory().hasTools(Scope.APPLICATION)) { 38 ctx.addToolbox(tm.getToolboxFactory().createToolbox( 39 Scope.APPLICATION)); 40 } 41 if (tm.getToolboxFactory().hasTools(Scope.SESSION)) { 42 ctx.addToolbox(tm.getToolboxFactory().createToolbox( 43 Scope.SESSION)); 44 } 45 } 46 return ctx; 47 } 48 }
然后在spring mvc的servlet配置文件中参考如下设置:
1 <bean 2 class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"> 3 <property name="order" value="0" /> 4 <property name="cache" value="true" /> 5 <property name="prefix" value="" /> 6 <property name="suffix" value=".vm" /> 7 <property name="toolboxConfigLocation" value="/WEB-INF/toolbox.xml" /> 8 <property name="contentType" value="text/html;charset=UTF-8" /> 9 <property name="viewClass" value="org.springframework.web.servlet.view.velocity.VelocityToolbox2View"></property> 10 </bean>
2. 如何获取当前应用的contextPath
1 <tool> 2 <key>link</key> 3 <scope>request</scope> 4 <class>org.apache.velocity.tools.view.LinkTool</class> 5 </tool>
借助velocity-tools的LinkTool类,在velocity中直接用${link.contextPath}即可得到当前的contextPath
3、如何获取url参数
1 <tool> 2 <key>params</key> 3 <scope>request</scope> 4 <class>org.apache.velocity.tools.view.ParameterTool</class> 5 </tool>
然后就可以用类似$params.returnUrl,来获取类似 http://xxx.com/login?returnUrl=abc 中的 abc部分
velocity模板引擎学习(2)-velocity tools 2.0
标签:
原文地址:http://www.cnblogs.com/yjmyzz/p/4188749.html