1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.apache.struts2.components.template;
23
24 import java.io.IOException;
25 import java.io.Writer;
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.struts2.ServletActionContext;
34 import org.apache.struts2.views.velocity.VelocityManager;
35 import org.apache.velocity.app.VelocityEngine;
36 import org.apache.velocity.context.Context;
37
38 import com.opensymphony.xwork2.inject.Inject;
39 import com.opensymphony.xwork2.util.logging.Logger;
40 import com.opensymphony.xwork2.util.logging.LoggerFactory;
41
42 /***
43 * Velocity based template engine.
44 */
45 public class VelocityTemplateEngine extends BaseTemplateEngine {
46 private static final Logger LOG = LoggerFactory.getLogger(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<Template> templates = templateContext.getTemplate().getPossibleTemplates(this);
68
69
70 org.apache.velocity.Template template = null;
71 String templateName = null;
72 Exception exception = null;
73 for (Template t : templates) {
74 templateName = getFinalTemplateName(t);
75 try {
76
77 template = velocityEngine.getTemplate(templateName);
78 break;
79 } catch (IOException e) {
80 if (exception == null) {
81 exception = e;
82 }
83 }
84 }
85
86 if (template == null) {
87 LOG.error("Could not load template " + templateContext.getTemplate());
88 if (exception != null) {
89 throw exception;
90 } else {
91 return;
92 }
93 }
94
95 if (LOG.isDebugEnabled()) {
96 LOG.debug("Rendering template " + templateName);
97 }
98
99 Context context = velocityManager.createContext(templateContext.getStack(), req, res);
100
101 Writer outputWriter = templateContext.getWriter();
102 context.put("tag", templateContext.getTag());
103 context.put("parameters", templateContext.getParameters());
104
105 template.merge(context, outputWriter);
106 }
107
108 protected String getSuffix() {
109 return "vm";
110 }
111 }