1 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 39 public class JsonView extends AbstractView { 40 41 private static final String DEFAULT_CONTENT_TYPE = 42 "text/plain; charset=UTF-8"; 43 44 private static final String JSON_HEADER = "X-JSON"; 45 46 private String characterEncoding = "UTF-8"; 47 48 private boolean sendAsHeader; 49 50 private String headerName = JSON_HEADER; 51 52 public JsonView() { 53 this(false); 54 } 55 56 public JsonView(boolean sendAsHeader) { 57 this.sendAsHeader = sendAsHeader; 58 setContentType(DEFAULT_CONTENT_TYPE); 59 } 60 61 public void setSendAsHeader(boolean sendAsHeader) { 62 this.sendAsHeader = sendAsHeader; 63 } 64 65 public void setHeaderName(String headerName) { 66 this.headerName = headerName; 67 } 68 69 public void setCharacterEncoding(String characterEncoding) { 70 this.characterEncoding = characterEncoding; 71 } 72 73 protected void renderMergedOutputModel(Map model, 74 HttpServletRequest request, HttpServletResponse response) 75 throws Exception { 76 77 response.setCharacterEncoding(characterEncoding); 78 JSONObject jsonObject = JSONObject.fromObject(model); 79 if (sendAsHeader) { 80 response.setHeader(headerName, jsonObject.toString()); 81 } 82 else { 83 PrintWriter out = response.getWriter(); 84 out.write('('); 85 out.write(jsonObject.toString()); 86 out.write(')'); 87 } 88 } 89 } | Popular Tags |