1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.struts2.sitemesh;
19
20 import java.io.IOException;
21 import java.io.PrintWriter;
22
23 import javax.servlet.ServletContext;
24 import javax.servlet.ServletException;
25 import javax.servlet.http.HttpServletRequest;
26 import javax.servlet.http.HttpServletResponse;
27
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30 import org.apache.struts2.views.velocity.VelocityManager;
31 import org.apache.velocity.Template;
32 import org.apache.velocity.context.Context;
33
34 import com.opensymphony.module.sitemesh.Decorator;
35 import com.opensymphony.module.sitemesh.HTMLPage;
36 import com.opensymphony.module.sitemesh.Page;
37 import com.opensymphony.xwork2.ActionContext;
38
39
40 /***
41 * Applies Velocity-based decorators
42 *
43 */
44 public class VelocityPageFilter extends TemplatePageFilter {
45 private static final Log LOG = LogFactory.getLog(VelocityPageFilter.class);
46
47 /***
48 * Applies the decorator, using the relevent contexts
49 *
50 * @param page The page
51 * @param decorator The decorator
52 * @param req The servlet request
53 * @param res The servlet response
54 * @param servletContext The servlet context
55 * @param ctx The action context for this request, populated with the server state
56 */
57 protected void applyDecorator(Page page, Decorator decorator,
58 HttpServletRequest req, HttpServletResponse res,
59 ServletContext servletContext, ActionContext ctx)
60 throws ServletException, IOException {
61 try {
62 VelocityManager vm = VelocityManager.getInstance();
63
64
65 vm.init(servletContext);
66
67
68 String encoding = getEncoding();
69
70
71 Template template = vm.getVelocityEngine().getTemplate(decorator.getPage(), encoding);
72 Context context = vm.createContext(ctx.getValueStack(), req, res);
73
74
75 context.put("page", page);
76 if (page instanceof HTMLPage) {
77 HTMLPage htmlPage = ((HTMLPage) page);
78 context.put("head", htmlPage.getHead());
79 }
80 context.put("title",page.getTitle());
81 context.put("body",page.getBody());
82
83
84 PrintWriter writer = res.getWriter();
85 template.merge(context, writer);
86 writer.flush();
87 } catch (Exception e) {
88 String msg = "Error applying decorator: " + e.getMessage();
89 LOG.error(msg, e);
90 throw new ServletException(msg, e);
91 }
92 }
93 }