`
xinklabi
  • 浏览: 1560298 次
  • 性别: Icon_minigender_1
  • 来自: 吉林
文章分类
社区版块
存档分类
最新评论

Struts2返回JSON数据的具体应用范例(转)

 
阅读更多

早在我刚学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数据到客户端:

 

Java代码 复制代码 收藏代码
  1. package cn.ysh.studio.struts2.json.demo.servlet;   
  2.   
  3. import java.io.IOException;   
  4. import java.io.PrintWriter;   
  5.   
  6. import javax.servlet.ServletException;   
  7. import javax.servlet.http.HttpServlet;   
  8. import javax.servlet.http.HttpServletRequest;   
  9. 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. }  
package cn.ysh.studio.struts2.json.demo.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import cn.ysh.studio.struts2.json.demo.bean.User;

public class JSON extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		//将要被返回到客户端的对象
		User user=new User();
		user.setId("123");
		user.setName("JSONServlet");
		user.setPassword("JSON");
		user.setSay("Hello , i am a servlet !");
		JSONObject json=new JSONObject();
		json.accumulate("success", true);
		json.accumulate("user", user);
		out.println(json.toString());
//		因为JSON数据在传递过程中是以普通字符串形式传递的,所以我们也可以手动拼接符合JSON语法规范的字符串输出到客户端
//		以下这两句的作用与38-46行代码的作用是一样的,将向客户端返回一个User对象,和一个success字段
//		String jsonString="{\"user\":{\"id\":\"123\",\"name\":\"JSONServlet\",\"say\":\"Hello , i am a servlet !\",\"password\":\"JSON\"},\"success\":true}";
//		out.println(jsonString);
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

 

结果在意料之中,如下图所示:

 

 

 

 

使用JSP(或html等)返回JSON数据到客户端:

 

Java代码 复制代码 收藏代码
  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}  
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
{"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数据的做法如出一辙:

 

Java代码 复制代码 收藏代码
  1. public String testByJSP() {   
  2.         User user = new User();   
  3.         user.setId("123");   
  4.         user.setName("Struts2");   
  5.         user.setPassword("123");   
  6.         user.setSay("Hello world !");   
  7.         JSONObject jsonObject=new JSONObject();   
  8.         jsonObject.accumulate("user", user);   
  9.         //这里在request对象中放了一个data,所以struts的result配置中不能有type="redirect"   
  10.         ServletActionContext.getRequest().setAttribute("data", jsonObject.toString());   
  11.         return SUCCESS;   
  12.     };  
public String testByJSP() {
		User user = new User();
		user.setId("123");
		user.setName("Struts2");
		user.setPassword("123");
		user.setSay("Hello world !");
		JSONObject jsonObject=new JSONObject();
		jsonObject.accumulate("user", user);
		//这里在request对象中放了一个data,所以struts的result配置中不能有type="redirect"
		ServletActionContext.getRequest().setAttribute("data", jsonObject.toString());
		return SUCCESS;
	};

 

因为是常规的Struts流程配置,所以配置内容就不再展示了。

 

JSP代码就非常简单了,

 

Java代码 复制代码 收藏代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>   
  2. ${data }  
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
${data }

 

结果如图所示:

 

 

 

 

在Action中以传统方式输出JSON数据


这一点跟传统的Servlet的处理方式基本上一模一样,代码如下

 

Java代码 复制代码 收藏代码
  1. public void doAction() throws IOException{   
  2.         HttpServletResponse response=ServletActionContext.getResponse();   
  3.         //以下代码从JSON.java中拷过来的   
  4.         response.setContentType("text/html");   
  5.         PrintWriter out;   
  6.         out = response.getWriter();   
  7.         //将要被返回到客户端的对象   
  8.         User user=new User();   
  9.         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.     }  
public void doAction() throws IOException{
		HttpServletResponse response=ServletActionContext.getResponse();
		//以下代码从JSON.java中拷过来的
		response.setContentType("text/html");
		PrintWriter out;
		out = response.getWriter();
		//将要被返回到客户端的对象
		User user=new User();
		user.setId("123");
		user.setName("JSONActionGeneral");
		user.setPassword("JSON");
		user.setSay("Hello , i am a action to print a json!");
		JSONObject json=new JSONObject();
		json.accumulate("success", true);
		json.accumulate("user", user);
		out.println(json.toString());
//		因为JSON数据在传递过程中是以普通字符串形式传递的,所以我们也可以手动拼接符合JSON语法规范的字符串输出到客户端
//		以下这两句的作用与38-46行代码的作用是一样的,将向客户端返回一个User对象,和一个success字段
//		String jsonString="{\"user\":{\"id\":\"123\",\"name\":\"JSONActionGeneral\",\"say\":\"Hello , i am a action to print a json!\",\"password\":\"JSON\"},\"success\":true}";
//		out.println(jsonString);
		out.flush();
		out.close();
	}

 

struts.xml中的配置:

 

Java代码 复制代码 收藏代码
  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>  
<package name="default" extends="struts-default" namespace="/">
	<action name="testJSONFromActionByGeneral" class="cn.ysh.studio.struts2.json.demo.action.UserAction" method="doAction">
	</action>
</package>

 

注意:这个action没有result,且doAction方法没有返回值!

 

就不再贴图了,因为结果可想而知!

 

 

在Action中以Struts2的方式输出JSON数据

本着“不重复发明轮子”的原则,我们将转换JSON数据的工作交给Struts2来做,那么相对于在Action中以传统方式输出JSON不同的是,Action是需要将注意力放在业务处理上,而无需关心处理结果是如何被转换成JSON被返回客户端的——这些 工作通过简单的配置,Struts2会帮我们做的更好。

 

Java代码 复制代码 收藏代码
  1. public String testByAction() {   
  2.         // dataMap中的数据将会被Struts2转换成JSON字符串,所以这里要先清空其中的数据   
  3.         dataMap.clear();   
  4.         User user = new User();   
  5.         user.setId("123");   
  6.         user.setName("JSONActionStruts2");   
  7.         user.setPassword("123");   
  8.         user.setSay("Hello world !");   
  9.         dataMap.put("user", user);   
  10.         // 放入一个是否操作成功的标识   
  11.         dataMap.put("success"true);   
  12.         // 返回结果   
  13.         return SUCCESS;   
  14.     }  
public String testByAction() {
		// dataMap中的数据将会被Struts2转换成JSON字符串,所以这里要先清空其中的数据
		dataMap.clear();
		User user = new User();
		user.setId("123");
		user.setName("JSONActionStruts2");
		user.setPassword("123");
		user.setSay("Hello world !");
		dataMap.put("user", user);
		// 放入一个是否操作成功的标识
		dataMap.put("success", true);
		// 返回结果
		return SUCCESS;
	}

 

 

struts.xml中action的配置:

 

Java代码 复制代码 收藏代码
  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>  
<package name="json" extends="json-default" namespace="/test">
		<action name="testByAction"
			class="cn.ysh.studio.struts2.json.demo.action.UserAction" method="testByAction">
			<result type="json">
				<!-- 这里指定将被Struts2序列化的属性,该属性在action中必须有对应的getter方法 -->
				<param name="root">dataMap</param>
			</result>
		</action>
</package>

 

凡是使用Struts2序列化对象到JSON的action,所在的package必须继承自json-default,注意,这里唯一的result,没有指定name属性。

 

结果如下图所示:

 

 

 

上面很详细的说明了在WEB应用中如何返回JSON数据到客户端,讲了那么多种方式,涉及的技术核心无非只有两点:


1、将对象转换成符合JSON语法格式的字符串;
2、将符合JSON语法格式的字符串返回客户端;


第二点是整个实现过程的本质,但却不难做到;第一点其实也不难,他甚至有两种做法,一是通过字符串拼接方式,而是通过JSONObject以对象方式转换。看下面的一个例子:

 

Java代码 复制代码 收藏代码
  1. package cn.ysh.studio.struts2.json.demo.test;   
  2.   
  3. import cn.ysh.studio.struts2.json.demo.bean.User;   
  4. import net.sf.json.JSONObject;   
  5.   
  6. public class JSONTest {   
  7.   
  8.     /**  
  9.      * 将普通的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. }  
package cn.ysh.studio.struts2.json.demo.test;

import cn.ysh.studio.struts2.json.demo.bean.User;
import net.sf.json.JSONObject;

public class JSONTest {

	/**
	 * 将普通的pojo转换成JSON字符串
	 * @return
	 */
	public JSONObject bean2json() {
		User user = new User();
		user.setId("JSONTest");
		user.setName("JSONTest");
		user.setPassword("JSON");
		user.setSay("Hello,i am JSONTest.java");
		JSONObject jsonObject = new JSONObject();
		jsonObject.accumulate("user", user);
		System.out.println("User转换后的字符串:"+jsonObject.toString());
		return jsonObject;
	}

	/**
	 * 从JSONObject对象中反向解析出User对象
	 * @param jsonObject
	 */
	public void json2bean(JSONObject jsonObject) {
		User user=(User)JSONObject.toBean((JSONObject)jsonObject.get("user"),User.class);
		System.out.println("转换得到的User对象的Name为:"+user.getName());
	}

	public static void main(String[] s) {
		JSONTest tester=new JSONTest();
		tester.json2bean(tester.bean2json());
	}
}

 

 

JSON格式的字符串返回到客户端后,客户端会将其解析并封装成真正的JSON对象,以供JS调用。

 


总结上述,其实只要明白了服务器返回JSON数据到客户端的原理,做起来就游刃有余了,他甚至有非常多的可选方案,但既然是基于Struts2的实现,那么肯定还是要用Struts2的方式来做啦,因为这样确实可以省很多事。另外,在文章的最后,说明一下返回JSON数据时在result中配置的参数的含义及其常见常见配置吧:

 

Java代码 复制代码 收藏代码
  1. <result type="json">   
  2.                 <!-- 这里指定将被Struts2序列化的属性,该属性在action中必须有对应的getter方法 -->   
  3.                 <!-- 默认将会序列所有有返回值的getter方法的值,而无论该方法是否有对应属性 -->   
  4.                 <param name="root">dataMap</param>   
  5.                 <!-- 指定是否序列化空的属性 -->   
  6.                 <param name="excludeNullProperties">true</param>   
  7.                 <!-- 这里指定将序列化dataMap中的那些属性 -->   
  8.                 <param name="includeProperties">   
  9.                     userList.*   
  10.                 </param>   
  11.                 <!-- 这里指定将要从dataMap中排除那些属性,这些排除的属性将不被序列化,一半不与上边的参数配置同时出现 -->   
  12.                 <param name="excludeProperties">   
  13.                     SUCCESS   
  14.                 </param>   
  15. </result>  
<result type="json">
				<!-- 这里指定将被Struts2序列化的属性,该属性在action中必须有对应的getter方法 -->
				<!-- 默认将会序列所有有返回值的getter方法的值,而无论该方法是否有对应属性 -->
				<param name="root">dataMap</param>
				<!-- 指定是否序列化空的属性 -->
				<param name="excludeNullProperties">true</param>
				<!-- 这里指定将序列化dataMap中的那些属性 -->
				<param name="includeProperties">
     				userList.*
				</param>
				<!-- 这里指定将要从dataMap中排除那些属性,这些排除的属性将不被序列化,一半不与上边的参数配置同时出现 -->
				<param name="excludeProperties">
     				SUCCESS
				</param>
</result>

 

值得一提的是通过Struts2来返回JSON数据,在IE中会提示下载,这个不用关心,换个浏览器就能正常展示JSON数据,而在JS调用中,更是毫无影响。

 

下面是整个Action的完整代码:

 

Java代码 复制代码 收藏代码
  1. package cn.ysh.studio.struts2.json.demo.action;   
  2.   
  3. import java.io.IOException;   
  4. import java.io.PrintWriter;   
  5. import java.util.HashMap;   
  6. import java.util.Map;   
  7.   
  8. import javax.servlet.http.HttpServletResponse;   
  9.   
  10. import org.apache.struts2.ServletActionContext;   
  11.   
  12. import net.sf.json.JSONObject;   
  13.   
  14. import cn.ysh.studio.struts2.json.demo.bean.User;   
  15.   
  16. import com.opensymphony.xwork2.ActionSupport;   
  17.   
  18. public class UserAction extends ActionSupport {   
  19.   
  20.     /**  
  21.      *   
  22.      */  
  23.     private static final long serialVersionUID = 1L;   
  24.   
  25.     //将会被Struts2序列化为JSON字符串的对象   
  26.     private Map<String, Object> dataMap;   
  27.   
  28.     /**  
  29.      * 构造方法  
  30.      */  
  31.     public UserAction() {   
  32.         //初始化Map对象   
  33.         dataMap = new HashMap<String, Object>();   
  34.     }   
  35.   
  36.     /**  
  37.      * 测试通过action以视图方式返回JSON数据  
  38.      * @return  
  39.      */  
  40.     public String testByJSP() {   
  41.         User user = new User();   
  42.         user.setId("123");   
  43.         user.setName("JSONActionJSP");   
  44.         user.setPassword("123");   
  45.         user.setSay("Hello world !");   
  46.         JSONObject jsonObject=new JSONObject();   
  47.         jsonObject.accumulate("user", user);   
  48.         jsonObject.accumulate("success"true);   
  49.         //这里在request对象中放了一个data,所以struts的result配置中不能有type="redirect"   
  50.         ServletActionContext.getRequest().setAttribute("data", jsonObject.toString());   
  51.         return SUCCESS;   
  52.     };   
  53.   
  54.     /**  
  55.      * 测试通过action以Struts2默认方式返回JSON数据  
  56.      * @return  
  57.      */  
  58.     public String testByAction() {   
  59.         // dataMap中的数据将会被Struts2转换成JSON字符串,所以这里要先清空其中的数据   
  60.         dataMap.clear();   
  61.         User user = new User();   
  62.         user.setId("123");   
  63.         user.setName("JSONActionStruts2");   
  64.         user.setPassword("123");   
  65.         user.setSay("Hello world !");   
  66.         dataMap.put("user", user);   
  67.         // 放入一个是否操作成功的标识   
  68.         dataMap.put("success"true);   
  69.         // 返回结果   
  70.         return SUCCESS;   
  71.     }   
  72.   
  73.     /**  
  74.      * 通过action是以传统方式返回JSON数据  
  75.      * @throws IOException  
  76.      */  
  77.     public void doAction() throws IOException{   
  78.         HttpServletResponse response=ServletActionContext.getResponse();   
  79.         //以下代码从JSON.java中拷过来的   
  80.         response.setContentType("text/html");   
  81.         PrintWriter out;   
  82.         out = response.getWriter();   
  83.         //将要被返回到客户端的对象   
  84.         User user=new User();   
  85.         user.setId("123");   
  86.         user.setName("JSONActionGeneral");   
  87.         user.setPassword("JSON");   
  88.         user.setSay("Hello , i am a action to print a json!");   
  89.         JSONObject json=new JSONObject();   
  90.         json.accumulate("success"true);   
  91.         json.accumulate("user", user);   
  92.         out.println(json.toString());   
  93. //      因为JSON数据在传递过程中是以普通字符串形式传递的,所以我们也可以手动拼接符合JSON语法规范的字符串输出到客户端   
  94. //      以下这两句的作用与38-46行代码的作用是一样的,将向客户端返回一个User对象,和一个success字段   
  95. //      String jsonString="{\"user\":{\"id\":\"123\",\"name\":\"JSONActionGeneral\",\"say\":\"Hello , i am a action to print a json!\",\"password\":\"JSON\"},\"success\":true}";   
  96. //      out.println(jsonString);   
  97.         out.flush();   
  98.         out.close();   
  99.     }   
  100.        
  101.     /**  
  102.      * Struts2序列化指定属性时,必须有该属性的getter方法,实际上,如果没有属性,而只有getter方法也是可以的  
  103.      * @return  
  104.      */  
  105.     public Map<String, Object> getDataMap() {   
  106.         return dataMap;   
  107.     }   
  108.   
  109. }  
package cn.ysh.studio.struts2.json.demo.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import net.sf.json.JSONObject;

import cn.ysh.studio.struts2.json.demo.bean.User;

import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	//将会被Struts2序列化为JSON字符串的对象
	private Map<String, Object> dataMap;

	/**
	 * 构造方法
	 */
	public UserAction() {
		//初始化Map对象
		dataMap = new HashMap<String, Object>();
	}

	/**
	 * 测试通过action以视图方式返回JSON数据
	 * @return
	 */
	public String testByJSP() {
		User user = new User();
		user.setId("123");
		user.setName("JSONActionJSP");
		user.setPassword("123");
		user.setSay("Hello world !");
		JSONObject jsonObject=new JSONObject();
		jsonObject.accumulate("user", user);
		jsonObject.accumulate("success", true);
		//这里在request对象中放了一个data,所以struts的result配置中不能有type="redirect"
		ServletActionContext.getRequest().setAttribute("data", jsonObject.toString());
		return SUCCESS;
	};

	/**
	 * 测试通过action以Struts2默认方式返回JSON数据
	 * @return
	 */
	public String testByAction() {
		// dataMap中的数据将会被Struts2转换成JSON字符串,所以这里要先清空其中的数据
		dataMap.clear();
		User user = new User();
		user.setId("123");
		user.setName("JSONActionStruts2");
		user.setPassword("123");
		user.setSay("Hello world !");
		dataMap.put("user", user);
		// 放入一个是否操作成功的标识
		dataMap.put("success", true);
		// 返回结果
		return SUCCESS;
	}

	/**
	 * 通过action是以传统方式返回JSON数据
	 * @throws IOException
	 */
	public void doAction() throws IOException{
		HttpServletResponse response=ServletActionContext.getResponse();
		//以下代码从JSON.java中拷过来的
		response.setContentType("text/html");
		PrintWriter out;
		out = response.getWriter();
		//将要被返回到客户端的对象
		User user=new User();
		user.setId("123");
		user.setName("JSONActionGeneral");
		user.setPassword("JSON");
		user.setSay("Hello , i am a action to print a json!");
		JSONObject json=new JSONObject();
		json.accumulate("success", true);
		json.accumulate("user", user);
		out.println(json.toString());
//		因为JSON数据在传递过程中是以普通字符串形式传递的,所以我们也可以手动拼接符合JSON语法规范的字符串输出到客户端
//		以下这两句的作用与38-46行代码的作用是一样的,将向客户端返回一个User对象,和一个success字段
//		String jsonString="{\"user\":{\"id\":\"123\",\"name\":\"JSONActionGeneral\",\"say\":\"Hello , i am a action to print a json!\",\"password\":\"JSON\"},\"success\":true}";
//		out.println(jsonString);
		out.flush();
		out.close();
	}
	
	/**
	 * Struts2序列化指定属性时,必须有该属性的getter方法,实际上,如果没有属性,而只有getter方法也是可以的
	 * @return
	 */
	public Map<String, Object> getDataMap() {
		return dataMap;
	}

}

 

完整的struts.xml配置文件如下:

 

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"    
  3.     "http://struts.apache.org/dtds/struts-2.0.dtd">  
  4. <struts>  
  5.     <package name="json" extends="json-default" namespace="/test">  
  6.         <action name="testByAction"  
  7.             class="cn.ysh.studio.struts2.json.demo.action.UserAction" method="testByAction">  
  8.             <result type="json">  
  9.                 <!-- 这里指定将被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>  
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 
	"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name="json" extends="json-default" namespace="/test">
		<action name="testByAction"
			class="cn.ysh.studio.struts2.json.demo.action.UserAction" method="testByAction">
			<result type="json">
				<!-- 这里指定将被Struts2序列化的属性,该属性在action中必须有对应的getter方法 -->
				<!-- 默认将会序列所有有返回值的getter方法的值,而无论该方法是否有对应属性 -->
				<param name="root">dataMap</param>
				<!-- 指定是否序列化空的属性 -->
				<!--
				<param name="excludeNullProperties">true</param>
				-->
				<!-- 这里指定将序列化dataMap中的那些属性 -->
				<!-- 
				<param name="includeProperties">
     				userList.*
				</param>
				 -->
				<!-- 这里指定将要从dataMap中排除那些属性,这些排除的属性将不被序列化,一半不与上边的参数配置同时出现 -->
				<!-- 
				<param name="excludeProperties">
     				SUCCESS
				</param>
				-->
			</result>
		</action>
	</package>
	<package name="default" extends="struts-default" namespace="/">
		<action name="testJSONFromActionByGeneral"
			class="cn.ysh.studio.struts2.json.demo.action.UserAction" method="doAction">
		</action>
		<action name="testByJSP"
			class="cn.ysh.studio.struts2.json.demo.action.UserAction" method="testByJSP">
			<result name="success">/actionJSP.jsp</result>
		</action>
	</package>
</struts>

 

 

最后,附上整个范例工程(一个MyEclipse工程)源码。

 

 

 

 

 

 原创文章,转载请注明出处:http://yshjava.iteye.com/blog/1333104

 

 

 

 

 

 

  • 大小: 28 KB
  • 大小: 44.7 KB
  • 大小: 22.5 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics