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