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