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