package com.jfinal.render;import java.io.IOException;import java.io.Writer;import java.util.Properties;import javax.servlet.ServletContext;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.velocity.Template;import org.apache.velocity.app.Velocity;import org.apache.velocity.app.VelocityEngine;import org.apache.velocity.context.Context;import org.apache.velocity.io.VelocityWriter;import org.apache.velocity.runtime.RuntimeConstants;import org.apache.velocity.tools.view.ToolboxManager;import org.apache.velocity.tools.view.context.ChainedContext;import org.apache.velocity.tools.view.servlet.ServletToolboxManager;import org.apache.velocity.util.SimplePool;@SuppressWarnings("deprecation")public class VelocityWithToolboxRender extends Render{ private static final String TOOL_BOX_CONF_FILE ="/WEB-INF/toolbox.xml"; private static final String encoding = getEncoding(); private static final String contentType = "text/html;charset=" + encoding; protected ToolboxManager toolboxManager = null; private static SimplePool writerPool = new SimplePool(40); public VelocityWithToolboxRender(String view) { this.view = view; initToolbox(RenderFactory.getServletContext()); } static { String webPath = RenderFactory.getServletContext().getRealPath("/"); Properties properties = new Properties(); properties.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, webPath); properties.setProperty(RuntimeConstants.ENCODING_DEFAULT, encoding); properties.setProperty(RuntimeConstants.INPUT_ENCODING, encoding); properties.setProperty(RuntimeConstants.OUTPUT_ENCODING, encoding); Velocity.init(properties); } protected void initToolbox(ServletContext servletContext) { toolboxManager = ServletToolboxManager.getInstance(servletContext, TOOL_BOX_CONF_FILE); } @SuppressWarnings("unchecked") protected Context createContext(HttpServletRequest req, HttpServletResponse resp) { ChainedContext ctx = new ChainedContext(new VelocityEngine(), req, resp, RenderFactory.getServletContext()); if (toolboxManager != null) { ctx.setToolbox(toolboxManager.getToolbox(ctx)); } return ctx; } @Override public void render() { Context context = createContext(request, response); VelocityWriter vw = null; Template template = Velocity.getTemplate(view); response.setContentType(contentType); try { Writer writer = response.getWriter(); vw = (VelocityWriter) writerPool.get(); if (vw == null) { vw = new VelocityWriter(writer, 4 * 1024, true); } else { vw.recycle(writer); } template.merge(context, vw); } catch (IOException e) { } finally { if (vw != null) { try { vw.flush(); vw.recycle(null); writerPool.put(vw); } catch (Exception e) { Velocity .debug("VelocityViewServlet: " + "Trouble releasing VelocityWriter: " + e.getMessage()); } } } }}
用法如下:写一个BaseController
@Override public void render(String view) { super.render(new VelocityWithToolboxRender(view)); }
因为我的项目中展现层用的是Velocity,所以可以直接覆盖super class的render方法。