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.views.freemarker;
23
24 import javax.servlet.ServletContext;
25 import javax.servlet.http.HttpServletRequest;
26 import javax.servlet.http.HttpSession;
27
28 import com.opensymphony.xwork2.util.ValueStack;
29
30 import freemarker.template.ObjectWrapper;
31 import freemarker.template.SimpleHash;
32 import freemarker.template.TemplateModel;
33 import freemarker.template.TemplateModelException;
34
35
36 /***
37 * Simple Hash model that also searches other scopes.
38 * <p/>
39 * If the key doesn't exist in this hash, this template model tries to
40 * resolve the key within the attributes of the following scopes,
41 * in the order stated: Request, Session, Servlet Context
42 */
43 public class ScopesHashModel extends SimpleHash {
44
45 private static final long serialVersionUID = 5551686380141886764L;
46
47 private HttpServletRequest request;
48 private ServletContext servletContext;
49 private ValueStack stack;
50
51
52 public ScopesHashModel(ObjectWrapper objectWrapper, ServletContext context, HttpServletRequest request, ValueStack stack) {
53 super(objectWrapper);
54 this.servletContext = context;
55 this.request = request;
56 this.stack = stack;
57 }
58
59
60 public TemplateModel get(String key) throws TemplateModelException {
61
62 TemplateModel model = super.get(key);
63
64 if (model != null) {
65 return model;
66 }
67
68
69 if (stack != null) {
70 Object obj = stack.findValue(key);
71
72 if (obj != null) {
73 return wrap(obj);
74 }
75
76
77 obj = stack.getContext().get(key);
78 if (obj != null) {
79 return wrap(obj);
80 }
81 }
82
83 if (request != null) {
84
85 Object obj = request.getAttribute(key);
86
87 if (obj != null) {
88 return wrap(obj);
89 }
90
91
92 HttpSession session = request.getSession(false);
93
94 if (session != null) {
95 obj = session.getAttribute(key);
96
97 if (obj != null) {
98 return wrap(obj);
99 }
100 }
101 }
102
103 if (servletContext != null) {
104
105 Object obj = servletContext.getAttribute(key);
106
107 if (obj != null) {
108 return wrap(obj);
109 }
110 }
111
112 return null;
113 }
114
115 public void put(String string, boolean b) {
116 super.put(string, b);
117 }
118
119 public void put(String string, Object object) {
120 super.put(string, object);
121 }
122 }