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