1 16 17 package org.springframework.web.servlet.view.velocity; 18 19 import java.lang.reflect.Method ; 20 import java.util.Map ; 21 22 import javax.servlet.http.HttpServletRequest ; 23 import javax.servlet.http.HttpServletResponse ; 24 25 import org.apache.velocity.VelocityContext; 26 import org.apache.velocity.context.Context; 27 import org.apache.velocity.tools.view.ToolboxManager; 28 import org.apache.velocity.tools.view.context.ChainedContext; 29 import org.apache.velocity.tools.view.servlet.ServletToolboxManager; 30 import org.apache.velocity.tools.view.tools.ViewTool; 31 32 import org.springframework.util.ClassUtils; 33 import org.springframework.util.ReflectionUtils; 34 35 70 public class VelocityToolboxView extends VelocityView { 71 72 private String toolboxConfigLocation; 73 74 75 85 public void setToolboxConfigLocation(String toolboxConfigLocation) { 86 this.toolboxConfigLocation = toolboxConfigLocation; 87 } 88 89 92 protected String getToolboxConfigLocation() { 93 return this.toolboxConfigLocation; 94 } 95 96 97 103 protected Context createVelocityContext( 104 Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { 105 106 ChainedContext velocityContext = new ChainedContext( 108 new VelocityContext(model), getVelocityEngine(), request, response, getServletContext()); 109 110 if (getToolboxConfigLocation() != null) { 112 ToolboxManager toolboxManager = ServletToolboxManager.getInstance( 113 getServletContext(), getToolboxConfigLocation()); 114 Map toolboxContext = toolboxManager.getToolbox(velocityContext); 115 velocityContext.setToolbox(toolboxContext); 116 } 117 118 return velocityContext; 119 } 120 121 128 protected void initTool(Object tool, Context velocityContext) throws Exception { 129 if (tool instanceof ViewTool) { 134 ((ViewTool) tool).init(velocityContext); 136 } 137 else { 138 Method initMethod = 140 ClassUtils.getMethodIfAvailable(tool.getClass(), "init", new Class [] {Object .class}); 141 if (initMethod != null) { 142 ReflectionUtils.invokeMethod(initMethod, tool, new Object [] {velocityContext}); 143 } 144 } 145 } 146 147 } 148 | Popular Tags |