View Javadoc

1   /*
2    * Copyright 2004-2008 the Seasar Foundation and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.seasar.cubby.action;
17  
18  import java.io.Writer;
19  
20  import javax.servlet.http.HttpServletRequest;
21  import javax.servlet.http.HttpServletResponse;
22  
23  import org.seasar.cubby.controller.ActionContext;
24  import org.seasar.framework.util.JSONSerializer;
25  import org.seasar.framework.util.StringUtil;
26  
27  /**
28   * JSON 形式のレスポンスを返す {@link ActionResult} です。
29   * <p>
30   * アクションメソッドの戻り値としてこのインスタンスを指定することで、指定された JavaBean を JSON/JSONP
31   * 形式に変換してレスポンスを返します。 ブラウザの JavaScript から発行されたリクエストを処理する場合等に使用してください。
32   * </p>
33   * <p>
34   * 使用例1 : JSON 形式のレスポンスを返す
35   * 
36   * <pre>
37   * MyBean bean = ...;
38   * return new Json(bean);
39   * </pre>
40   * 
41   * </p>
42   * <p>
43   * 使用例2 : コールバック関数名を指定して JSONP 形式のレスポンスを返す
44   * 
45   * <pre>
46   * MyBean bean = ...;
47   * return new Json(bean, &quot;callback&quot;);
48   * </pre>
49   * 
50   * </p>
51   * 
52   * @see <a href="http://www.json.org/">JSON(JavaScript Object Notation)</a>
53   * @see <a href="http://ajaxian.com/archives/jsonp-json-with-padding">JSONP(JSON
54   *      with Padding)</a>
55   * @see JSONSerializer#serialize(Object)
56   * @author baba
57   * @since 1.0.0
58   */
59  public class Json extends AbstractActionResult {
60  
61  	private Object bean;
62  
63  	private String calllback;
64  
65  	/**
66  	 * JSON 形式でレスポンスを返すインスタンスを生成します。
67  	 * 
68  	 * @param bean
69  	 *            JSON 形式に変換する JavaBean
70  	 */
71  	public Json(final Object bean) {
72  		this(bean, null);
73  	}
74  
75  	/**
76  	 * JSONP 形式でレスポンスを返すインスタンスを生成します。
77  	 * 
78  	 * @param bean
79  	 *            JSON 形式に変換する JavaBean
80  	 * @param callback
81  	 *            コールバック関数名
82  	 */
83  	public Json(final Object bean, final String callback) {
84  		this.bean = bean;
85  		this.calllback = callback;
86  	}
87  
88  	/**
89  	 * JSON 形式に変換する JavaBeanを取得します。
90  	 * 
91  	 * @return JSON 形式に変換する JavaBean
92  	 */
93  	public Object getBean() {
94  		return this.bean;
95  	}
96  
97  	/**
98  	 * コールバック関数名を取得します。
99  	 * 
100 	 * @return コールバック関数名
101 	 */
102 	public String getCallback() {
103 		return this.calllback;
104 	}
105 
106 	/**
107 	 * {@inheritDoc}
108 	 */
109 	public void execute(final ActionContext context,
110 			final HttpServletRequest request, final HttpServletResponse response)
111 			throws Exception {
112 
113 		response.setContentType("text/javascript; charset=utf-8");
114 		response.setHeader("Cache-Control", "no-cache");
115 		response.setHeader("Pragma", "no-cache");
116 
117 		final String script;
118 		if (isJsonp()) {
119 			script = appendCallbackFunction(JSONSerializer.serialize(bean),
120 					calllback);
121 		} else {
122 			script = JSONSerializer.serialize(bean);
123 		}
124 
125 		final Writer writer = response.getWriter();
126 		writer.write(script);
127 		writer.flush();
128 	}
129 
130 	private boolean isJsonp() {
131 		return !StringUtil.isEmpty(calllback);
132 	}
133 
134 	private static String appendCallbackFunction(final String script,
135 			final String callback) {
136 		final StringBuilder builder = new StringBuilder(script.length()
137 				+ callback.length() + 10);
138 		builder.append(callback);
139 		builder.append("(");
140 		builder.append(script);
141 		builder.append(");");
142 		return builder.toString();
143 	}
144 
145 }