8、使用Struts2实现异步调用机制剖析(XML与JSON方式解析)

综合使用jquery,struts2实现XML数据和JSON数据的解析

1、解析XML

一个输入提交页面getXML.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'getXML.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript" src="scripts/jquery-1.9.1.js"></script>
	
	<script type="text/javascript">
		function getInfo()
		{
			$.post("getXMLAction.action",
					{
						name:$("#name").val()
					},function(returnedData,status)
					{
						var id = $(returnedData).find("id").text();
						var name = $(returnedData).find("name").text();
						var age = $(returnedData).find("age").text();
						var address = $(returnedData).find("address").text();

						var html = "<table width='60%' border='1' align='center'><tr><th>id</th><th>name</th><th>address</th><th>age</th></tr><tr align='center'><td>" + id + "</td><td>" + name + "</td><td>" + address + "</td><td>" + age + "</td></tr></table>"

						$("#theBody table:eq(0)").remove();
						
						$("#theBody").append(html); 
					});
		}
	</script>
  </head>
  
  <body id="theBody">
    <select id="name">
    	<option value="zhangsan">zhangsan</option>
    	<option value="lisi">lisi</option>
    </select>
    <input type="button" value="click" οnclick="getInfo();"/>
  </body>
</html>


一个action:

package com.cdtax.action.xml;



import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.opensymphony.xwork2.ActionSupport;

public class GetXMLAction extends ActionSupport
{
	private String name;

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}
	
	@Override
	public String execute() throws Exception
	{
		Person person1 = new Person();
		
		person1.setId(1);
		person1.setName("zhangsan");
		person1.setAge(20);
		person1.setAddress("beijing");
		
		Person person2 = new Person();
		person2.setId(2);
		person2.setName("lisi");
		person2.setAge(30);
		person2.setAddress("shanghai");
		
		Document document = DocumentHelper.createDocument();
		
		Element rootElement = document.addElement("persons");
		
		rootElement.addComment("this is commnets");
		
		Element e = rootElement.addElement("person");
		
		Element idElement = e.addElement("id");
		Element nameElement = e.addElement("name");
		Element ageElement = e.addElement("age");
		Element addressElement = e.addElement("address");
		
		if("zhangsan".equals(name))
		{
			idElement.setText(person1.getId() + "");
			nameElement.setText(person1.getName());
			ageElement.setText(person1.getAge() + "");
			addressElement.setText(person1.getAddress());
		}
		else
		{
			idElement.setText(person2.getId() + "");
			nameElement.setText(person2.getName());
			ageElement.setText(person2.getAge() + "");
			addressElement.setText(person2.getAddress());
		}
		
		HttpServletResponse response = ServletActionContext.getResponse();
		
		response.setContentType("text/xml;charset=utf-8");
		response.setHeader("cache-control", "no-cache");
		
		PrintWriter out = response.getWriter();
		
		OutputFormat format = OutputFormat.createCompactFormat();
		format.setEncoding("utf-8");
		
		XMLWriter writer = new XMLWriter(out,format);
		
		writer.write(document);
		out.flush();
		out.close();
		
		return null;		
	}
}


配置struts.xml中的action:

<action name="getXMLAction" class="com.cdtax.action.xml.GetXMLAction">
		
</action>


2、解析JSON

一个提交页面getJson.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'json.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<script type="text/javascript" src="scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(function()
{
	$("#button1").click(function()
	{
		$.post("getJsonAction",{name:$("#name").val()},
				function(returnedData,status)
		{
			
				var person = returnedData;
				var id = person.id;
				var name = person.name;
				var age = person.age;
				var address = person.address;

				var html = "<table width='60%' border='1' align='center'><tr><th>id</th><th>name</th><th>address</th><th>age</th></tr><tr align='center'><td>" + id + "</td><td>" + name + "</td><td>" + address + "</td><td>" + age + "</td></tr></table>"

				$("#theBody table:eq(0)").remove();
				
				$("#theBody").append(html); 
			
		});
	});
});

</script>
  </head>
  
  <body id="theBody">
    <select id="name">
    	<option value="zhangsan">zhangsan</option>
    	<option value="lisi">lisi</option>
    </select>
    <input type="button" value="ddfds" id="button1">
  </body>
</html>


处理的action:

package com.cdtax.action.json;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.cdtax.action.xml.Person;
import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;

public class GetJsonAction extends ActionSupport
{
	private String name;

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}
	
	@Override
	public String execute() throws Exception
	{
		Person person = new Person();
		person.setId(1);
		person.setName(name);
		person.setAge(30);
		person.setAddress("shanghai");
		
		Gson gson = new Gson();
		String result = gson.toJson(person);
//		System.out.println(result);
		
		HttpServletResponse response = ServletActionContext.getResponse();
		
		response.setContentType("text/json;charset=utf-8");
		response.setHeader("cache-control", "no-cache");
		
		PrintWriter out = response.getWriter();
		
		out.print(result);
		out.flush();
		out.close();
		return null;
	}
}


配置action,略

3、struts2提供了json插件,struts2-json-plugin-2.3.14.jar

提交页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'json.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<script type="text/javascript" src="scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(function()
{
	$("#button1").click(function()
	{
		$.post("getJsonAction2.action",{name:$("#name").val()},
				function(returnedData,status)
		{
			
				var person = returnedData;
				var id = person.id;
				var name = person.name;
				var age = person.age;
				var address = person.address;

				var html = "<table width='60%' border='1' align='center'><tr><th>id</th><th>name</th><th>address</th><th>age</th></tr><tr align='center'><td>" + id + "</td><td>" + name + "</td><td>" + address + "</td><td>" + age + "</td></tr></table>"

				$("#theBody table:eq(0)").remove();
				
				$("#theBody").append(html); 
			
		});
	});
});

</script>
  </head>
  
  <body id="theBody">
    <select id="name">
    	<option value="zhangsan">zhangsan</option>
    	<option value="lisi">lisi</option>
    </select>
    <input type="button" value="ddfds" id="button1">
  </body>
</html>


一个Action:

package com.cdtax.action.json;

import org.apache.struts2.json.annotations.JSON;

import com.opensymphony.xwork2.ActionSupport;

public class GetJsonAction2 extends ActionSupport
{
	private String name;
	private int id;
	private int age;
	private String address;
	public String getName()
	{
		return name;
	}
	public void setName(String name)
	{
		this.name = name;
	}
	public int getId()
	{
		return id;
	}
	public void setId(int id)
	{
		this.id = id;
	}
	@JSON(name="myAge")
	public int getAge()
	{
		return age;
	}
	public void setAge(int age)
	{
		this.age = age;
	}
	public String getAddress()
	{
		return address;
	}
	public void setAddress(String address)
	{
		this.address = address;
	}
	
	@Override
	public String execute() throws Exception
	{
		this.id = 1;
		this.age = 30;
		this.address = "shanghai";
		System.out.println("invoke!!!!!!!!!!!!!!!");
		
		return SUCCESS;
	}
}


配置文件struts.xml中进行action的配置:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
	
	<package name="struts2_ajax" extends="json-default">
		<action name="getXMLAction" class="com.cdtax.action.xml.GetXMLAction">
		
		</action>
		<action name="getJsonAction" class="com.cdtax.action.json.GetJsonAction">
		
		</action>
		
		<action name="getJsonAction2" class="com.cdtax.action.json.GetJsonAction2">
			<result name="success" type="json">
				<param name="excludeProperties">address</param>
			</result>
		</action>
	</package>
	
	
</struts>


注意这里的package要extends的是json-default

result标签可以包含<param name="excludeProperties">address</param>,表示服务器端排除的成员变量,即这个变量数据没有在发往客户端的json数据中。在Action中,还可以使用注解来给某个变量重新命名,就是发给客户端的变量名,如

@JSON(name="myAge")
public int getAge()
{
return age;
}

在客户端,得到的就是myAge,而不是age

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值