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