001
014
015 package com.liferay.portal.struts;
016
017 import com.liferay.portal.kernel.servlet.HttpHeaders;
018 import com.liferay.portal.kernel.util.ContentTypes;
019 import com.liferay.portal.kernel.util.ParamUtil;
020 import com.liferay.portal.kernel.util.Validator;
021 import com.liferay.portal.util.PortalUtil;
022
023 import java.io.PrintWriter;
024
025 import javax.servlet.http.HttpServletRequest;
026 import javax.servlet.http.HttpServletResponse;
027
028 import org.apache.struts.action.Action;
029 import org.apache.struts.action.ActionForm;
030 import org.apache.struts.action.ActionForward;
031 import org.apache.struts.action.ActionMapping;
032
033
036 public abstract class JSONAction extends Action {
037
038 public ActionForward execute(
039 ActionMapping mapping, ActionForm form, HttpServletRequest request,
040 HttpServletResponse response)
041 throws Exception {
042
043 String callback = ParamUtil.getString(request, "callback");
044 String instance = ParamUtil.getString(request, "inst");
045
046 String json = null;
047
048 try {
049 json = getJSON(mapping, form, request, response);
050
051 if (Validator.isNotNull(callback)) {
052 json = callback + "(" + json + ");";
053 }
054 else if (Validator.isNotNull(instance)) {
055 json = "var " + instance + "=" + json + ";";
056 }
057 }
058 catch (Exception e) {
059 PortalUtil.sendError(
060 HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e, request,
061 response);
062
063 return null;
064 }
065
066 if (Validator.isNotNull(json)) {
067 response.setContentType(ContentTypes.TEXT_JAVASCRIPT);
068 response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");
069
070 PrintWriter pw = response.getWriter();
071
072 pw.write(json);
073
074 pw.close();
075 }
076
077 return null;
078 }
079
080 public abstract String getJSON(
081 ActionMapping mapping, ActionForm form, HttpServletRequest request,
082 HttpServletResponse response)
083 throws Exception;
084
085 }