Struts2-支持JSON

作者:聂勇 欢迎转载,请保留作者信息并说明文章来源!

思路:通过Result将Action中指定的数据序列化成JSON。

工作环境(Runtime Enviroment)

  • struts2-2.1.6
  • json-lib-2.3-jdk15.jar
  • flexjson-1.9.2.jar
  • ezmorph-1.0.6.jar
  • commons-lang-2.5.jar
  • commons-collections-3.2.1.jar

实现步骤(Step By Step)

1、编写JSON Result类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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);
}
}

2、在Struts2中配置result type。

1
2
3
4
5
6
7
<result-types>
<result-type name="json" class="cn.aofeng.common.util.json.JSONResult">
<param name="jsonObjectProperty">jsonObject</param>
<param name="contentType">application/json</param>
<param name="encoding">UTF-8</param>
</result-type>
</result-types>

3、在Action中返回JSON数据。
1)公共代码部分。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* 响应类型:JSON.
*/
protected final static String JSON = "json";
private JSONObject _jsonObject = new JSONObject();
public JSONObject getJsonObject() {
return _jsonObject;
}
/**
* 添加需转化成JSON的数据.
*
* @param key 键.
* @param value 值.
*/
protected void putJsonElement(String key, Object value) {
_jsonObject.put(key, value);
}

2)各Action实际应用部分示例。

1
2
3
4
5
6
7
public String execute() throws Exception {
List<String> data = new ArrayList();
data.add(something);
putJsonElemnt("dataList", data);
return JSON;
}

参考资料(Reference)

1、http://struts.apache.org/2.0.14/struts2-core/apidocs/org/apache/struts2/dispatcher/StrutsResultSupport.html