我的补充:
在struts2的基础上 配置 struts2还需要的包:
commons-lang-2.4.jar;
json-lib-2.3-jdk13.jar;
jsonplugin-0[1].32.jar;
ezmorph-1.0.2.jar;
commons-beanutils-1.7.0.jar;
另外,可以通过: @JSON(name="mymessage") 来给 action 中的get属性设 json节点 别名
通过给 属性设置: @JSON(serialize=false) 来给控制 哪些属性 不序列化输出.
我的异常就是: 因为我的 action 中有 service 接口对象属性,所以导致 序列化成 json 失败 而异常了
多了去了,
root:只包含xx对象
excludeProperties :除了xx之外的集合
includeProperties : 包含xx的集合
wrapPrefix :json结果开头添加xx(比如<paramname="wrapPrefix">[</param>)
wrapSuffix :同上,只不过是结尾
ignoreHierarchy :转化时是否忽略继承关系true/false
enumAsBean : 是否将枚举当做一个bean处理
enableGZIP :是否支持gzip压缩输出
noCache :是否缓存
excludeNullProperties : 是否转化输出 null值
statusCode :设置响应代号比如 304
callbackParameter : JSONP跨域访问的回调设置
contentType : 输出类型
大概就这么多了,还有几个是低版本的,已经废弃了,就不列出了
以下摘自: http://www.open-open.com/lib/view/open1325518231062.html
早在我刚学Struts2之初的时候,就想写一篇文章来阐述Struts2如何返回JSON数据的原理和具体应用了,但苦于一直忙于工作难以抽身,渐渐的也淡忘了此事。直到前两天有同事在工作中遇到这个问题,来找我询问,我又细细地给他讲了一遍之后,才觉得无论如何要抽一个小时的时间来写这篇文章,从头到尾将Struts2与JSON的关系说清楚。
其实网络中,关于这个问题的答案已是海量,我当初也是从这海量的答案中吸收精华,才将“Struts2返回JSON数据”这个问题搞清楚的。但是这些海量的答案,有一个共同的缺陷,就是作者们只关注问题核心,即“如何在具体的Struts2应用中返回JSON数据到客户端”如何实现,而对于"为何要这样实现"以及实现的本质却解释的不甚了了,在笔者看来这只是“授人以鱼”而非笔者所推崇的“授人以鱼的同时,授人以渔”。在这篇文章中,笔者将总结前辈们的经验,并结合自己的理解,来从理论到实践由浅入深的说明“Struts2返回JSON数据”这一问题。
JSON(JavaScript Object Notation)
首先来看一下JSON官方对于“JSON”的解释:
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。(更多内容请参见JSON官网http://json.org/json-zh.html)
JSON建构于两种结构:
“名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。
值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。
因为JSON中的值(value)可以是双引号括起来的字符串(string)、数值(number)、true、false、 null、对象(object)或者数组(array),且这些结构可以嵌套,这种特性给予JSON表达数据以无限的可能:它既可以表达一个简单的 key/value,也可以表达一个复杂的Map或List,而且它是易于阅读和理解的。
Struts2中JSON的用武之地
因为JSON是脱离语言的理想的数据交换格式,所以它被频繁的应用在客户端与服务器的通信过程中,这一点是毋庸置疑的。而在客户端与服务器的通信过程中,JSON数据的传递又被分为服务器向客户端传送JSON数据,和客户端向服务器传送JSON数据,前者的核心过程中将对象转换成JSON,而后者的核心是将JSON转换成对象,这是本质的区别。另外,值得一提的是,JSON数据在传递过程中,其实就是传递一个普通的符合JSON语法格式的字符串而已,所谓的“JSON对象”是指对这个JSON字符串解析和包装后的结果,这一点请牢记,因为下面的内容会依赖这一点。
Struts2返回JSON数据到客户端
这是最常见的需求,在AJAX大行其道的今天,向服务器请求JSON数据已成为每一个WEB应用必备的功能。抛开Struts2暂且不提,在常规WEB应用中由服务器返回JSON数据到客户端有两种方式:一是在Servlet中输出JSON串,二是在JSP页面中输出JSON串。上文提到,服务器像客户端返回JSON数据,其实就是返回一个符合JSON语法规范的字符串,所以在上述两种 方法中存在一个共同点,就是将需要返回的数据包装称符合JSON语法规范的字符串后在页面中显示。如下所示
使用Servlet返回JSON数据到客户端:
01 |
package cn.ysh.studio.struts2.json.demo.servlet; |
02 |
03 |
import java.io.IOException; |
04 |
import java.io.PrintWriter; |
05 |
06 |
import javax.servlet.ServletException; |
07 |
import javax.servlet.http.HttpServlet; |
08 |
import javax.servlet.http.HttpServletRequest; |
09 |
import javax.servlet.http.HttpServletResponse; |
10 |
11 |
import net.sf.json.JSONObject; |
12 |
13 |
import cn.ysh.studio.struts2.json.demo.bean.User; |
14 |
15 |
public class JSON extends HttpServlet { |
16 |
17 |
/** |
18 |
* |
19 |
*/ |
20 |
private static final long serialVersionUID = 1L; |
21 |
22 |
/** |
23 |
* The doGet method of the servlet. <br> |
24 |
* |
25 |
* This method is called when a form has its tag value method equals to get. |
26 |
* |
27 |
* @param request the request send by the client to the server |
28 |
* @param response the response send by the server to the client |
29 |
* @throws ServletException if an error occurred |
30 |
* @throws IOException if an error occurred |
31 |
*/ |
32 |
public void doGet(HttpServletRequest request, HttpServletResponse response) |
33 |
throws ServletException, IOException { |
34 |
35 |
response.setContentType( "text/html" ); |
36 |
PrintWriter out = response.getWriter(); |
37 |
//将要被返回到客户端的对象 |
38 |
User user= new User(); |
39 |
user.setId( "123" ); |
40 |
user.setName( "JSONServlet" ); |
41 |
user.setPassword( "JSON" ); |
42 |
user.setSay( "Hello , i am a servlet !" ); |
43 |
JSONObject json= new JSONObject(); |
44 |
json.accumulate( "success" , true ); |
45 |
json.accumulate( "user" , user); |
46 |
out.println(json.toString()); |
47 |
// 因为JSON数据在传递过程中是以普通字符串形式传递的,所以我们也可以手动拼接符合JSON语法规范的字符串输出到客户端 |
48 |
// 以下这两句的作用与38-46行代码的作用是一样的,将向客户端返回一个User对象,和一个success字段 |
49 |
// String jsonString="{\"user\":{\"id\":\"123\",\"name\":\"JSONServlet\",\"say\":\"Hello , i am a servlet !\",\"password\":\"JSON\"},\"success\":true}"; |
50 |
// out.println(jsonString); |
51 |
out.flush(); |
52 |
out.close(); |
53 |
} |
54 |
55 |
/** |
56 |
* The doPost method of the servlet. <br> |
57 |
* |
58 |
* This method is called when a form has its tag value method equals to post. |
59 |
* |
60 |
* @param request the request send by the client to the server |
61 |
* @param response the response send by the server to the client |
62 |
* @throws ServletException if an error occurred |
63 |
* @throws IOException if an error occurred |
64 |
*/ |
65 |
public void doPost(HttpServletRequest request, HttpServletResponse response) |
66 |
throws ServletException, IOException { |
67 |
doGet(request, response); |
68 |
} |
69 |
70 |
} |
结果在意料之中,如下图所示:
使用JSP(或html等)返回JSON数据到客户端:
1 |
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> |
2 |
{"user":{"id":"123","name":"JSONJSP","say":"Hello , i am a JSP !","password":"JSON"},"success":true} |
这个就不用去看结果了吧。
再回到Struts,在Struts的MVC模型中,Action替代Servlet担当了Model的角色,所以对于Struts而言,返回 JSON数据到客户端,跟传统的WEB应用一样,存在两种方式,即在Action中输出JSON数据,和在视图资源中输出JSON数据。再往下细分的话,在Action中输出JSON数据又分为两种方式,一是使用传统方式输出自己包装后的JSON数据,二是使用Struts自带的JSON数据封装功能来自动包装并返回JSON数据。
在视图资源中输出JSON数据
Action处理完用户请求后,将数据存放在某一位置,如request中,并返回视图,然后Struts将跳转至该视图资源,在该视图中,我们需要做的是将数据从存放位置中取出,然后将其转换为JSON字符串,输出在视图中。这跟传统WEB应用中在JSP页面输出JSON数据的做法如出一辙:
01 |
public String testByJSP() { |
02 |
User user = new User(); |
03 |
user.setId( "123" ); |
04 |
user.setName( "Struts2" ); |
05 |
user.setPassword( "123" ); |
06 |
user.setSay( "Hello world !" ); |
07 |
JSONObject jsonObject= new JSONObject(); |
08 |
jsonObject.accumulate( "user" , user); |
09 |
//这里在request对象中放了一个data,所以struts的result配置中不能有type="redirect" |
10 |
ServletActionContext.getRequest().setAttribute( "data" , jsonObject.toString()); |
11 |
return SUCCESS; |
12 |
}; |
因为是常规的Struts流程配置,所以配置内容就不再展示了。
JSP代码就非常简单了,
1 |
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> |
2 |
${data } |
结果如图所示:
在Action中以传统方式输出JSON数据
这一点跟传统的Servlet的处理方式基本上一模一样,代码如下
01 |
public void doAction() throws IOException{ |
02 |
HttpServletResponse response=ServletActionContext.getResponse(); |
03 |
//以下代码从JSON.java中拷过来的 |
04 |
response.setContentType( "text/html" ); |
05 |
PrintWriter out; |
06 |
out = response.getWriter(); |
07 |
//将要被返回到客户端的对象 |
08 |
User user= new User(); |
09 |
user.setId( "123" ); |
10 |
user.setName( "JSONActionGeneral" ); |
11 |
user.setPassword( "JSON" ); |
12 |
user.setSay( "Hello , i am a action to print a json!" ); |
13 |
JSONObject json= new JSONObject(); |
14 |
json.accumulate( "success" , true ); |
15 |
json.accumulate( "user" , user); |
16 |
out.println(json.toString()); |
17 |
// 因为JSON数据在传递过程中是以普通字符串形式传递的,所以我们也可以手动拼接符合JSON语法规范的字符串输出到客户端 |
18 |
// 以下这两句的作用与38-46行代码的作用是一样的,将向客户端返回一个User对象,和一个success字段 |
19 |
// String jsonString="{\"user\":{\"id\":\"123\",\"name\":\"JSONActionGeneral\",\"say\":\"Hello , i am a action to print a json!\",\"password\":\"JSON\"},\"success\":true}"; |
20 |
// out.println(jsonString); |
21 |
out.flush(); |
22 |
out.close(); |
23 |
} |
struts.xml中的配置:
1 |
< package name = "default" extends = "struts-default" namespace = "/" > |
2 |
< action name = "testJSONFromActionByGeneral" class = "cn.ysh.studio.struts2.json.demo.action.UserAction" method = "doAction" > |
3 |
</ action > |
4 |
</ package > |
注意:这个action没有result,且doAction方法没有返回值!
就不再贴图了,因为结果可想而知!
在Action中以Struts2的方式输出JSON数据
本着“不重复发明轮子”的原则,我们将转换JSON数据的工作交给Struts2来做,那么相对于在Action中以传统方式输出JSON不同的是,Action是需要将注意力放在业务处理上,而无需关心处理结果是如何被转换成JSON被返回客户端的——这些 工作通过简单的配置,Struts2会帮我们做的更好。
01 |
public String testByAction() { |
02 |
// dataMap中的数据将会被Struts2转换成JSON字符串,所以这里要先清空其中的数据 |
03 |
dataMap.clear(); |
04 |
User user = new User(); |
05 |
user.setId( "123" ); |
06 |
user.setName( "JSONActionStruts2" ); |
07 |
user.setPassword( "123" ); |
08 |
user.setSay( "Hello world !" ); |
09 |
dataMap.put( "user" , user); |
10 |
// 放入一个是否操作成功的标识 |
11 |
dataMap.put( "success" , true ); |
12 |
// 返回结果 |
13 |
return SUCCESS; |
14 |
} |
struts.xml中action的配置:
1 |
< package name = "json" extends = "json-default" namespace = "/test" > |
2 |
< action name = "testByAction" |
3 |
class = "cn.ysh.studio.struts2.json.demo.action.UserAction" method = "testByAction" > |
4 |
< result type = "json" > |
5 |
<!-- 这里指定将被Struts2序列化的属性,该属性在action中必须有对应的getter方法 --> |
6 |
< param name = "root" >dataMap</ param > |
7 |
</ result > |
8 |
</ action > |
9 |
</ package > |
凡是使用Struts2序列化对象到JSON的action,所在的package必须继承自json-default,注意,这里唯一的result,没有指定name属性。
结果如下图所示:
上面很详细的说明了在WEB应用中如何返回JSON数据到客户端,讲了那么多种方式,涉及的技术核心无非只有两点:
1、将对象转换成符合JSON语法格式的字符串;
2、将符合JSON语法格式的字符串返回客户端;
第二点是整个实现过程的本质,但却不难做到;第一点其实也不难,他甚至有两种做法,一是通过字符串拼接方式,而是通过JSONObject以对象方式转换。看下面的一个例子:
01 |
package cn.ysh.studio.struts2.json.demo.test; |
02 |
03 |
import cn.ysh.studio.struts2.json.demo.bean.User; |
04 |
import net.sf.json.JSONObject; |
05 |
06 |
public class JSONTest { |
07 |
08 |
/** |
09 |
* 将普通的pojo转换成JSON字符串 |
10 |
* @return |
11 |
*/ |
12 |
public JSONObject bean2json() { |
13 |
User user = new User(); |
14 |
user.setId( "JSONTest" ); |
15 |
user.setName( "JSONTest" ); |
16 |
user.setPassword( "JSON" ); |
17 |
user.setSay( "Hello,i am JSONTest.java" ); |
18 |
JSONObject jsonObject = new JSONObject(); |
19 |
jsonObject.accumulate( "user" , user); |
20 |
System.out.println( "User转换后的字符串:" +jsonObject.toString()); |
21 |
return jsonObject; |
22 |
} |
23 |
24 |
/** |
25 |
* 从JSONObject对象中反向解析出User对象 |
26 |
* @param jsonObject |
27 |
*/ |
28 |
public void json2bean(JSONObject jsonObject) { |
29 |
User user=(User)JSONObject.toBean((JSONObject)jsonObject.get( "user" ),User. class ); |
30 |
System.out.println( "转换得到的User对象的Name为:" +user.getName()); |
31 |
} |
32 |
33 |
public static void main(String[] s) { |
34 |
JSONTest tester= new JSONTest(); |
35 |
tester.json2bean(tester.bean2json()); |
36 |
} |
37 |
} |
JSON格式的字符串返回到客户端后,客户端会将其解析并封装成真正的JSON对象,以供JS调用。
总结上述,其实只要明白了服务器返回JSON数据到客户端的原理,做起来就游刃有余了,他甚至有非常多的可选方案,但既然是基于 Struts2的实现,那么肯定还是要用Struts2的方式来做啦,因为这样确实可以省很多事。另外,在文章的最后,说明一下返回JSON数据时在 result中配置的参数的含义及其常见常见配置吧:
01 |
< result type = "json" > |
02 |
<!-- 这里指定将被Struts2序列化的属性,该属性在action中必须有对应的getter方法 --> |
03 |
<!-- 默认将会序列所有有返回值的getter方法的值,而无论该方法是否有对应属性 --> |
04 |
< param name = "root" >dataMap</ param > |
05 |
<!-- 指定是否序列化空的属性 --> |
06 |
< param name = "excludeNullProperties" >true</ param > |
07 |
<!-- 这里指定将序列化dataMap中的那些属性 --> |
08 |
< param name = "includeProperties" > |
09 |
userList.* |
10 |
</ param > |
11 |
<!-- 这里指定将要从dataMap中排除那些属性,这些排除的属性将不被序列化,一半不与上边的参数配置同时出现 --> |
12 |
< param name = "excludeProperties" > |
13 |
SUCCESS |
14 |
</ param > |
15 |
</ result > |
值得一提的是通过Struts2来返回JSON数据,在IE中会提示下载,这个不用关心,换个浏览器就能正常展示JSON数据,而在JS调用中,更是毫无影响。
下面是整个Action的完整代码:
001 |
package cn.ysh.studio.struts2.json.demo.action; |
002 |
003 |
import java.io.IOException; |
004 |
import java.io.PrintWriter; |
005 |
import java.util.HashMap; |
006 |
import java.util.Map; |
007 |
008 |
import javax.servlet.http.HttpServletResponse; |
009 |
010 |
import org.apache.struts2.ServletActionContext; |
011 |
012 |
import net.sf.json.JSONObject; |
013 |
014 |
import cn.ysh.studio.struts2.json.demo.bean.User; |
015 |
016 |
import com.opensymphony.xwork2.ActionSupport; |
017 |
018 |
public class UserAction extends ActionSupport { |
019 |
020 |
/** |
021 |
* |
022 |
*/ |
023 |
private static final long serialVersionUID = 1L; |
024 |
025 |
//将会被Struts2序列化为JSON字符串的对象 |
026 |
private Map<String, Object> dataMap; |
027 |
028 |
/** |
029 |
* 构造方法 |
030 |
*/ |
031 |
public UserAction() { |
032 |
//初始化Map对象 |
033 |
dataMap = new HashMap<String, Object>(); |
034 |
} |
035 |
036 |
/** |
037 |
* 测试通过action以视图方式返回JSON数据 |
038 |
* @return |
039 |
*/ |
040 |
public String testByJSP() { |
041 |
User user = new User(); |
042 |
user.setId( "123" ); |
043 |
user.setName( "JSONActionJSP" ); |
044 |
user.setPassword( "123" ); |
045 |
user.setSay( "Hello world !" ); |
046 |
JSONObject jsonObject= new JSONObject(); |
047 |
jsonObject.accumulate( "user" , user); |
048 |
jsonObject.accumulate( "success" , true ); |
049 |
//这里在request对象中放了一个data,所以struts的result配置中不能有type="redirect" |
050 |
ServletActionContext.getRequest().setAttribute( "data" , jsonObject.toString()); |
051 |
return SUCCESS; |
052 |
}; |
053 |
054 |
/** |
055 |
* 测试通过action以Struts2默认方式返回JSON数据 |
056 |
* @return |
057 |
*/ |
058 |
public String testByAction() { |
059 |
// dataMap中的数据将会被Struts2转换成JSON字符串,所以这里要先清空其中的数据 |
060 |
dataMap.clear(); |
061 |
User user = new User(); |
062 |
user.setId( "123" ); |
063 |
user.setName( "JSONActionStruts2" ); |
064 |
user.setPassword( "123" ); |
065 |
user.setSay( "Hello world !" ); |
066 |
dataMap.put( "user" , user); |
067 |
// 放入一个是否操作成功的标识 |
068 |
dataMap.put( "success" , true ); |
069 |
// 返回结果 |
070 |
return SUCCESS; |
071 |
} |
072 |
073 |
/** |
074 |
* 通过action是以传统方式返回JSON数据 |
075 |
* @throws IOException |
076 |
*/ |
077 |
public void doAction() throws IOException{ |
078 |
HttpServletResponse response=ServletActionContext.getResponse(); |
079 |
//以下代码从JSON.java中拷过来的 |
080 |
response.setContentType( "text/html" ); |
081 |
PrintWriter out; |
082 |
out = response.getWriter(); |
083 |
//将要被返回到客户端的对象 |
084 |
User user= new User(); |
085 |
user.setId( "123" ); |
086 |
user.setName( "JSONActionGeneral" ); |
087 |
user.setPassword( "JSON" ); |
088 |
user.setSay( "Hello , i am a action to print a json!" ); |
089 |
JSONObject json= new JSONObject(); |
090 |
json.accumulate( "success" , true ); |
091 |
json.accumulate( "user" , user); |
092 |
out.println(json.toString()); |
093 |
// 因为JSON数据在传递过程中是以普通字符串形式传递的,所以我们也可以手动拼接符合JSON语法规范的字符串输出到客户端 |
094 |
// 以下这两句的作用与38-46行代码的作用是一样的,将向客户端返回一个User对象,和一个success字段 |
095 |
// String jsonString="{\"user\":{\"id\":\"123\",\"name\":\"JSONActionGeneral\",\"say\":\"Hello , i am a action to print a json!\",\"password\":\"JSON\"},\"success\":true}"; |
096 |
// out.println(jsonString); |
097 |
out.flush(); |
098 |
out.close(); |
099 |
} |
100 |
|
101 |
/** |
102 |
* Struts2序列化指定属性时,必须有该属性的getter方法,实际上,如果没有属性,而只有getter方法也是可以的 |
103 |
* @return |
104 |
*/ |
105 |
public Map<String, Object> getDataMap() { |
106 |
return dataMap; |
107 |
} |
108 |
109 |
} |
完整的struts.xml配置文件如下:
01 |
<? xml version = "1.0" encoding = "UTF-8" ?> |
02 |
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" |
03 |
"http://struts.apache.org/dtds/struts-2.0.dtd"> |
04 |
< struts > |
05 |
< package name = "json" extends = "json-default" namespace = "/test" > |
06 |
< action name = "testByAction" |
07 |
class = "cn.ysh.studio.struts2.json.demo.action.UserAction" method = "testByAction" > |
08 |
< result type = "json" > |
09 |
<!-- 这里指定将被Struts2序列化的属性,该属性在action中必须有对应的getter方法 --> |
10 |
<!-- 默认将会序列所有有返回值的getter方法的值,而无论该方法是否有对应属性 --> |
11 |
< param name = "root" >dataMap</ param > |
12 |
<!-- 指定是否序列化空的属性 --> |
13 |
<!-- |
14 |
<param name="excludeNullProperties">true</param> |
15 |
--> |
16 |
<!-- 这里指定将序列化dataMap中的那些属性 --> |
17 |
<!-- |
18 |
<param name="includeProperties"> |
19 |
userList.* |
20 |
</param> |
21 |
--> |
22 |
<!-- 这里指定将要从dataMap中排除那些属性,这些排除的属性将不被序列化,一半不与上边的参数配置同时出现 --> |
23 |
<!-- |
24 |
<param name="excludeProperties"> |
25 |
SUCCESS |
26 |
</param> |
27 |
--> |
28 |
</ result > |
29 |
</ action > |
30 |
</ package > |
31 |
< package name = "default" extends = "struts-default" namespace = "/" > |
32 |
< action name = "testJSONFromActionByGeneral" |
33 |
class = "cn.ysh.studio.struts2.json.demo.action.UserAction" method = "doAction" > |
34 |
</ action > |
35 |
< action name = "testByJSP" |
36 |
class = "cn.ysh.studio.struts2.json.demo.action.UserAction" method = "testByJSP" > |
37 |
< result name = "success" >/actionJSP.jsp</ result > |
38 |
</ action > |
39 |
</ package > |
40 |
</ struts > |