org.zodiac.template.velocity.spring.view.servlet.ServletVelocityToolboxView Maven / Gradle / Ivy
The newest version!
package org.zodiac.template.velocity.spring.view.servlet;
import java.lang.reflect.Method;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.ToolboxFactory;
import org.apache.velocity.tools.view.VelocityView;
import org.apache.velocity.tools.view.ViewToolContext;
import org.apache.velocity.tools.view.ViewToolManager;
import org.springframework.util.ReflectionUtils;
import org.zodiac.commons.util.Classes;
public class ServletVelocityToolboxView extends ServletVelocityView {
private ToolboxFactory toolboxFactory;
private boolean userOverwrite = true;
protected ToolboxFactory getToolboxFactory() {
return toolboxFactory;
}
public void setToolboxFactory(ToolboxFactory toolboxFactory) {
this.toolboxFactory = toolboxFactory;
}
protected boolean isUserOverwrite() {
return userOverwrite;
}
public void setUserOverwrite(boolean userOverwrite) {
this.userOverwrite = userOverwrite;
}
/**
* Overridden to create a ChainedContext, which is part of the view package of Velocity Tools, as special context.
* ChainedContext is needed for initialization of ViewTool instances.
*
* @see #initTool
*/
@Override
protected Context createVelocityContext(Map model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
ViewToolContext velocityContext =
new ViewToolContext(getVelocityEngine(), request, response, getServletContext());
velocityContext.putAll(model);
// Load a Velocity Tools toolbox, if necessary.
if (getToolboxFactory() != null) {
ViewToolManager toolboxManager = new VelocityView(getServletContext());
toolboxManager.setVelocityEngine(getVelocityEngine());
toolboxManager.setToolboxFactory(getToolboxFactory());
toolboxManager.publishApplicationTools();
toolboxManager.publishToolboxes(request);
velocityContext.addToolbox(toolboxManager.getApplicationToolbox());
velocityContext.setUserCanOverwriteTools(userOverwrite);
}
return velocityContext;
}
/**
* Overridden to check for the ViewContext interface which is part of the view package of Velocity Tools. This
* requires a special Velocity context, like ChainedContext as set up by {@link #createVelocityContext} in this
* class.
*/
@Override
protected void initTool(Object tool, Context velocityContext) throws Exception {
// Velocity Tools 1.3: a class-level "init(Object)" method.
Method initMethod = Classes.getMethodIfAvailable(tool.getClass(), "init", Object.class);
if (initMethod != null) {
ReflectionUtils.invokeMethod(initMethod, tool, velocityContext);
}
}
}