1 package com.opensymphony.webwork.components.template; 2 3 import com.opensymphony.webwork.ServletActionContext; 4 import com.opensymphony.webwork.views.velocity.AbstractTagDirective; 5 import com.opensymphony.webwork.views.velocity.VelocityManager; 6 import com.opensymphony.xwork.ActionContext; 7 import org.apache.commons.logging.Log; 8 import org.apache.commons.logging.LogFactory; 9 import org.apache.velocity.app.VelocityEngine; 10 import org.apache.velocity.context.Context; 11 12 import javax.servlet.ServletContext ; 13 import javax.servlet.http.HttpServletRequest ; 14 import javax.servlet.http.HttpServletResponse ; 15 import java.io.IOException ; 16 import java.io.Writer ; 17 import java.util.Iterator ; 18 import java.util.List ; 19 import java.util.Map ; 20 21 27 public class VelocityTemplateEngine extends BaseTemplateEngine { 28 private static final Log LOG = LogFactory.getLog(VelocityTemplateEngine.class); 29 30 public void renderTemplate(TemplateRenderingContext templateContext) throws Exception { 31 Map actionContext = templateContext.getStack().getContext(); 33 ServletContext servletContext = (ServletContext ) actionContext.get(ServletActionContext.SERVLET_CONTEXT); 34 HttpServletRequest req = (HttpServletRequest ) actionContext.get(ServletActionContext.HTTP_REQUEST); 35 HttpServletResponse res = (HttpServletResponse ) actionContext.get(ServletActionContext.HTTP_RESPONSE); 36 37 VelocityManager velocityManager = VelocityManager.getInstance(); 39 velocityManager.init(servletContext); 40 VelocityEngine velocityEngine = velocityManager.getVelocityEngine(); 41 42 List templates = templateContext.getTemplate().getPossibleTemplates(this); 44 45 org.apache.velocity.Template template = null; 47 String templateName = null; 48 Exception exception = null; 49 for (Iterator iterator = templates.iterator(); iterator.hasNext();) { 50 Template t = (Template) iterator.next(); 51 templateName = getFinalTemplateName(t); 52 try { 53 template = velocityEngine.getTemplate(templateName); 55 break; 56 } catch (IOException e) { 57 if (exception == null) { 58 exception = e; 59 } 60 } 61 } 62 63 if (template == null) { 64 LOG.error("Could not load template " + templateContext.getTemplate()); 65 if (exception != null) { 66 throw exception; 67 } else { 68 return; 69 } 70 } 71 72 if (LOG.isDebugEnabled()) { 73 LOG.debug("Rendering template " + templateName); 74 } 75 76 Context context = velocityManager.createContext(templateContext.getStack(), req, res); 77 78 Writer outputWriter = (Writer ) ActionContext.getContext().get(AbstractTagDirective.VELOCITY_WRITER); 80 if (outputWriter == null) { 81 outputWriter = templateContext.getWriter(); 82 } 83 84 context.put("tag", templateContext.getTag()); 85 context.put("parameters", templateContext.getParameters()); 86 87 template.merge(context, outputWriter); 88 } 89 90 protected String getSuffix() { 91 return "vm"; 92 } 93 } 94 | Popular Tags |