01: /* ***** BEGIN LICENSE BLOCK *****
02: * Version: MPL 1.1
03: * The contents of this file are subject to the Mozilla Public License Version
04: * 1.1 (the "License"); you may not use this file except in compliance with
05: * the License. You may obtain a copy of the License at
06: * http://www.mozilla.org/MPL/
07: *
08: * Software distributed under the License is distributed on an "AS IS" basis,
09: * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
10: * for the specific language governing rights and limitations under the
11: * License.
12: *
13: * The Original Code is Riot.
14: *
15: * The Initial Developer of the Original Code is
16: * Neteye GmbH.
17: * Portions created by the Initial Developer are Copyright (C) 2006
18: * the Initial Developer. All Rights Reserved.
19: *
20: * Contributor(s):
21: * Felix Gnass [fgnass at neteye dot de]
22: *
23: * ***** END LICENSE BLOCK ***** */
24: package org.riotfamily.common.web.view;
25:
26: import java.io.PrintWriter;
27: import java.util.Map;
28:
29: import javax.servlet.http.HttpServletRequest;
30: import javax.servlet.http.HttpServletResponse;
31:
32: import net.sf.json.JSONObject;
33:
34: import org.springframework.web.servlet.view.AbstractView;
35:
36: /**
37: * A View that renders the model as JSON object.
38: */
39: public class JsonView extends AbstractView {
40:
41: private static final String DEFAULT_CONTENT_TYPE = "text/plain; charset=UTF-8";
42:
43: private static final String JSON_HEADER = "X-JSON";
44:
45: private String characterEncoding = "UTF-8";
46:
47: private boolean sendAsHeader;
48:
49: private String headerName = JSON_HEADER;
50:
51: public JsonView() {
52: this (false);
53: }
54:
55: public JsonView(boolean sendAsHeader) {
56: this .sendAsHeader = sendAsHeader;
57: setContentType(DEFAULT_CONTENT_TYPE);
58: }
59:
60: public void setSendAsHeader(boolean sendAsHeader) {
61: this .sendAsHeader = sendAsHeader;
62: }
63:
64: public void setHeaderName(String headerName) {
65: this .headerName = headerName;
66: }
67:
68: public void setCharacterEncoding(String characterEncoding) {
69: this .characterEncoding = characterEncoding;
70: }
71:
72: protected void renderMergedOutputModel(Map model,
73: HttpServletRequest request, HttpServletResponse response)
74: throws Exception {
75:
76: response.setCharacterEncoding(characterEncoding);
77: JSONObject jsonObject = JSONObject.fromObject(model);
78: if (sendAsHeader) {
79: response.setHeader(headerName, jsonObject.toString());
80: } else {
81: PrintWriter out = response.getWriter();
82: out.write('(');
83: out.write(jsonObject.toString());
84: out.write(')');
85: }
86: }
87: }
|