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