1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.seasar.cubby.action;
17
18 import java.io.Writer;
19 import java.lang.reflect.Method;
20 import java.util.Collection;
21 import java.util.Map;
22
23 import javax.servlet.http.HttpServletRequest;
24 import javax.servlet.http.HttpServletResponse;
25
26 import org.seasar.framework.util.JSONSerializer;
27 import org.seasar.framework.util.StringUtil;
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73 public class Json implements ActionResult {
74
75 private Object bean;
76
77 private String calllback;
78
79 private String contentType = "text/javascript";
80
81 private String encoding = "utf-8";
82
83
84
85
86
87
88
89 public Json(final Object bean) {
90 this(bean, null);
91 }
92
93
94
95
96
97
98
99
100
101 public Json(final Object bean, final String callback) {
102 this.bean = bean;
103 this.calllback = callback;
104 }
105
106
107
108
109
110
111 public Object getBean() {
112 return this.bean;
113 }
114
115
116
117
118
119
120 public String getCallback() {
121 return this.calllback;
122 }
123
124
125
126
127
128
129
130
131 public Json contentType(String contentType) {
132 this.contentType = contentType;
133 return this;
134 }
135
136
137
138
139
140
141 public String getContentType() {
142 return this.contentType;
143 }
144
145
146
147
148
149
150
151
152
153
154
155 public Json encoding(String encoding) {
156 this.encoding = encoding;
157 return this;
158 }
159
160
161
162
163
164
165 public String getEncoding() {
166 return this.encoding;
167 }
168
169
170
171
172 public void execute(final Action action,
173 final Class<? extends Action> actionClass, final Method method,
174 final HttpServletRequest request, final HttpServletResponse response)
175 throws Exception {
176 response.setCharacterEncoding(this.encoding);
177 response
178 .setContentType(this.contentType + "; charset=" + this.encoding);
179 response.setHeader("Cache-Control", "no-cache");
180 response.setHeader("Pragma", "no-cache");
181
182 final String script;
183 if (isJsonp()) {
184 script = appendCallbackFunction(JSONSerializer.serialize(bean),
185 calllback);
186 } else {
187 script = JSONSerializer.serialize(bean);
188 }
189
190 final Writer writer = response.getWriter();
191 writer.write(script);
192 writer.flush();
193 }
194
195 private boolean isJsonp() {
196 return !StringUtil.isEmpty(calllback);
197 }
198
199 private static String appendCallbackFunction(final String script,
200 final String callback) {
201 final StringBuilder builder = new StringBuilder(script.length()
202 + callback.length() + 10);
203 builder.append(callback);
204 builder.append("(");
205 builder.append(script);
206 builder.append(");");
207 return builder.toString();
208 }
209 }