1
22
23 package com.liferay.portal.struts;
24
25 import com.liferay.portal.kernel.servlet.HttpHeaders;
26 import com.liferay.portal.kernel.util.ContentTypes;
27 import com.liferay.portal.kernel.util.ParamUtil;
28 import com.liferay.portal.kernel.util.Validator;
29 import com.liferay.portal.util.PortalUtil;
30
31 import java.io.PrintWriter;
32
33 import javax.servlet.http.HttpServletRequest;
34 import javax.servlet.http.HttpServletResponse;
35
36 import org.apache.struts.action.Action;
37 import org.apache.struts.action.ActionForm;
38 import org.apache.struts.action.ActionForward;
39 import org.apache.struts.action.ActionMapping;
40
41
46 public abstract class JSONAction extends Action {
47
48 public ActionForward execute(
49 ActionMapping mapping, ActionForm form, HttpServletRequest request,
50 HttpServletResponse response)
51 throws Exception {
52
53 String callback = ParamUtil.getString(request, "callback");
54 String instance = ParamUtil.getString(request, "inst");
55
56 String json = null;
57
58 try {
59 json = getJSON(mapping, form, request, response);
60
61 if (Validator.isNotNull(callback)) {
62 json = callback + "(" + json + ");";
63 }
64 else if (Validator.isNotNull(instance)) {
65 json = "var " + instance + "=" + json + ";";
66 }
67 }
68 catch (Exception e) {
69 PortalUtil.sendError(
70 HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e, request,
71 response);
72
73 return null;
74 }
75
76 if (Validator.isNotNull(json)) {
77 response.setContentType(ContentTypes.TEXT_JAVASCRIPT);
78 response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");
79
80 PrintWriter pw = response.getWriter();
81
82 pw.write(json);
83
84 pw.close();
85 }
86
87 return null;
88 }
89
90 public abstract String getJSON(
91 ActionMapping mapping, ActionForm form, HttpServletRequest request,
92 HttpServletResponse response)
93 throws Exception;
94
95 }