1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 package groovy.servlet;
47
48 import groovy.lang.Binding;
49 import groovy.xml.MarkupBuilder;
50
51 import javax.servlet.http.HttpServletRequest;
52 import javax.servlet.ServletContext;
53 import javax.servlet.ServletResponse;
54 import java.util.Map;
55 import java.util.Enumeration;
56 import java.io.IOException;
57
58 /***
59 * Servlet-specific binding extesion to lazy load the writer or the output stream from the response.
60 * This binding also provide a markup builder named "html".
61 *
62 * @author Guillaume Laforge
63 */
64 public class ServletBinding extends Binding {
65
66 protected Binding binding = new Binding();
67 private ServletResponse response;
68 private MarkupBuilder html;
69
70 public ServletBinding(HttpServletRequest request, ServletResponse response, ServletContext sc) {
71 this.response = response;
72
73 binding.setVariable("request", request);
74 binding.setVariable("response", response);
75 binding.setVariable("context", sc);
76 binding.setVariable("application", sc);
77 binding.setVariable("session", request.getSession(true));
78
79
80 for (Enumeration paramEnum = request.getParameterNames(); paramEnum.hasMoreElements();) {
81 String key = (String) paramEnum.nextElement();
82 if (!binding.getVariables().containsKey(key)) {
83 String[] values = request.getParameterValues(key);
84 if (values.length == 1) {
85 binding.setVariable(key, values[0]);
86 } else {
87 binding.setVariable(key, values);
88 }
89 }
90 }
91 }
92
93 public void setVariable(String name, Object value) {
94 binding.setVariable(name, value);
95 }
96
97 public Map getVariables() {
98 return binding.getVariables();
99 }
100
101 /***
102 * @return a writer, an output stream, a markup builder or another requested object
103 */
104 public Object getVariable(String name) {
105 try {
106 if ("out".equals(name))
107 return response.getWriter();
108 if ("sout".equals(name))
109 return response.getOutputStream();
110 if ("html".equals(name)) {
111 if (html == null)
112 html = new MarkupBuilder(response.getWriter());
113 return html;
114 }
115 }
116 catch (IOException e) { }
117 return binding.getVariable(name);
118 }
119 }