1 5 package com.opensymphony.webwork.components.template; 6 7 import com.opensymphony.webwork.ServletActionContext; 8 import com.opensymphony.webwork.views.freemarker.FreemarkerManager; 9 import com.opensymphony.xwork.ActionContext; 10 import com.opensymphony.xwork.ActionInvocation; 11 import com.opensymphony.xwork.util.OgnlValueStack; 12 import freemarker.template.Configuration; 13 import freemarker.template.SimpleHash; 14 import org.apache.commons.logging.Log; 15 import org.apache.commons.logging.LogFactory; 16 17 import javax.servlet.ServletContext ; 18 import javax.servlet.http.HttpServletRequest ; 19 import javax.servlet.http.HttpServletResponse ; 20 import java.io.IOException ; 21 import java.util.Iterator ; 22 import java.util.List ; 23 import java.util.Map ; 24 25 28 public class FreemarkerTemplateEngine extends BaseTemplateEngine { 29 30 private static final Log LOG = LogFactory.getLog(FreemarkerTemplateEngine.class); 31 32 public void renderTemplate(TemplateRenderingContext templateContext) throws Exception { 33 OgnlValueStack stack = templateContext.getStack(); 35 Map context = stack.getContext(); 36 ServletContext servletContext = (ServletContext ) context.get(ServletActionContext.SERVLET_CONTEXT); 37 HttpServletRequest req = (HttpServletRequest ) context.get(ServletActionContext.HTTP_REQUEST); 38 HttpServletResponse res = (HttpServletResponse ) context.get(ServletActionContext.HTTP_RESPONSE); 39 40 FreemarkerManager freemarkerManager = FreemarkerManager.getInstance(); 42 Configuration config = freemarkerManager.getConfigruation(servletContext); 43 44 List templates = templateContext.getTemplate().getPossibleTemplates(this); 46 47 freemarker.template.Template template = null; 49 String templateName = null; 50 Exception exception = null; 51 for (Iterator iterator = templates.iterator(); iterator.hasNext();) { 52 Template t = (Template) iterator.next(); 53 templateName = getFinalTemplateName(t); 54 try { 55 template = config.getTemplate(templateName); 57 break; 58 } catch (IOException e) { 59 if (exception == null) { 60 exception = e; 61 } 62 } 63 } 64 65 if (template == null) { 66 LOG.error("Could not load template " + templateContext.getTemplate()); 67 if (exception != null) { 68 throw exception; 69 } else { 70 return; 71 } 72 } 73 74 if (LOG.isDebugEnabled()) { 75 LOG.debug("Rendering template " + templateName); 76 } 77 78 ActionInvocation ai = ActionContext.getContext().getActionInvocation(); 79 80 Object action = (ai == null) ? null : ai.getAction(); 81 SimpleHash model = freemarkerManager.buildTemplateModel(stack, action, servletContext, req, res, config.getObjectWrapper()); 82 83 model.put("tag", templateContext.getTag()); 84 model.put("parameters", templateContext.getParameters()); 85 86 template.process(model, templateContext.getWriter()); 87 } 88 89 protected String getSuffix() { 90 return "ftl"; 91 } 92 } 93 | Popular Tags |