package cn.aofeng.common.util.json;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsException;
import org.apache.struts2.dispatcher.StrutsResultSupport;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
* Struts2插件:JSON响应类型定义.
*
* @author aofeng
*/
public class JSONResult extends StrutsResultSupport {
private static final Logger _logger = Logger.getLogger(JSONResult.class);
private String jsonObjectProperty = "jsonObject";
private String contentType = JSONSerializerUtils.JSON_MIME_TYPE;
private String encoding = "UTF-8";
public JSONResult() {
}
public String getJSONObjectProperty() {
return jsonObjectProperty;
}
public void setJSONObjectProperty(String jsonObject) {
jsonObjectProperty = jsonObject;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public void doExecute(String finalLocation, ActionInvocation invocation)
throws Exception {
JSONObject jsonObject = getJSONObject(invocation);
if (jsonObject != null) {
String json = jsonObject.toString();
HttpServletResponse response = getServletResponse(invocation);
response.setContentType(getContentType());
response.setContentLength(json.getBytes(this.encoding).length);
OutputStream os = response.getOutputStream();
os.write(json.getBytes(this.encoding));
os.flush();
}
}
protected JSONObject getJSONObject(ActionInvocation invocation) {
ActionContext actionContext = invocation.getInvocationContext();
Object obj = actionContext.getValueStack().findValue(jsonObjectProperty);
if (obj == null) {
_logger.error("property [" + jsonObjectProperty + "] returns null, expecting JSONObject", new StrutsException("StrutsException"));
return null;
}
if (!(JSONObject.class).isInstance(obj)) {
_logger.error("property [" + jsonObjectProperty + "] is [" + obj + "] especting an instance of JSONObject", new StrutsException());
return null;
} else {
return (JSONObject) obj;
}
}
protected HttpServletResponse getServletResponse(ActionInvocation invocation) {
return (HttpServletResponse) invocation.getInvocationContext().get(ServletActionContext.HTTP_RESPONSE);
}
}