jquery+Ajax框架處理,XML,JSON,GSON物件傳送!詳解+案列!struts2的支援

java的爪哇發表於2013-07-24

先熱熱身!看看簡單的json,格式吧:

package acc.testJSON;

import org.json.JSONArray;
import org.json.JSONObject;

public class Test {

	/**
	 * json格式說明
	 * {}一個物件
	 * []一個陣列
	 * key:value
	 * JSONArray
	 * @param args
	 */
	public static void main(String[] args) {
		String json="{'user':'json','pass':'123'}";
		//解悉json格式字串
		JSONObject jsonObj=new JSONObject(json);
		String user=jsonObj.getString("user");
		String pass=jsonObj.getString("pass");
		System.out.println("user: "+user+"  \tpass:  "+pass);

		
		System.out.println("------------------------------>");
		//解析json陣列格式
		String jsonArray="[{'age':50, 'isOad':false, 'user':{'name':'胡錦濤', 'leve':100}},{'user':{'name':'習近平', 'leve':100}, 'age':333, 'isOad':true}]";
		JSONArray array=new JSONArray(jsonArray);
		
		for(int i=0;i<array.length();i++){
			//獲取第i個陣列內容,得到一個josn物件
			JSONObject obj=array.getJSONObject(i);
			//輸出josn物件的內容
			System.out.println("age: "+obj.getInt("age"));
			System.out.println("isOad: "+obj.getBoolean("isOad"));
			//獲取josn物件裡的 使用者物件
			JSONObject userJ=obj.getJSONObject("user");
			//輸出使用者物件
			System.out.println("name: "+userJ.getString("name")+"\tleve: "+userJ.getInt("leve"));
		}
		
	}

}

開始上主題!--------------------------------------------------

strtsu.xml 程式碼:

<?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>

<include file="jqueryAction.xml" />
<package name="default1" namespace="/" extends="json-default">

<!-- xml物件方式 -->
<action name="getXmlInfo" class="accp.struts2.GetXmlInfo"/>


<!-- json -->
<action name="getJsonInfo" class="accp.struts.json.GetJsonInfo">
<result name="success" type="json">
<!-- 排除屬性,不會序列化 -->
<param name="excludeProperties">myAge</param>
<!-- 指定序列化從那個根開始
<param name="root">person</param> -->
<!-- 序列化包括父類的屬性 -->
<param name="ignoreHierarchy">false</param>
<!-- 排除空值的屬性 -->
<param name="excludeNullProperties">true</param>
</result>
</action>


<!-- Gson Test -->
<action name="gsonAction" class="accp.struts.json.GetGsonAction">
</action>


</package>
</struts>


xml 現在一般不用這 個,太麻煩,流量重

效果


xml jsp頁面程式碼

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>My JSP 'xmlTest.jsp' starting page</title>
    <script type="text/javascript" src="jquery/jquery-1.9.1.js">
    
    </script>
    <script type="text/javascript">
	    /**
	    *ajax 第一個引數uri地址
	    *第二個引數:傳送過去的值
	    *第三個引數:反回的回撥函式(資料,狀態);
	    */
    
    function getInfo(){
    alert($("#name").val());
    $.post(
    "getXmlInfo.action", 
    { name:$("#name").val()},
    function(returnedDatas,status){ 
     if("success"==status) { 
     var id=$(returnedDatas).find("id").text();
     var name=$(returnedDatas).find("name").text();
     var age=$(returnedDatas).find("age").text();
     var adderss=$(returnedDatas).find("adderss").text();
    
     var htmls="<table width='980px' border='1' align='center'><tr> <td>id</td><th>name</th><th>age</th><th>adderss</th></tr><tr>"
     +"<td>"+id+"</td><td>"+name+"</td><td>"+age+"</td><td>"+adderss+"</td></tr></table>";
     $("body table:eq(0)").remove();
     $("#theBody").append(htmls);
   // alert(htmls);
    }
    }
    );
    }
    </script>

  </head>
  
  <body id="theBody">
    <select id="name">
     <option>劉備</option>
     <option>張三</option>
   </select>
   
   <input type="button" value="獲取資訊" onclick="getInfo()"/>
  </body>
</html>

xml action實現程式碼:

package accp.struts2;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

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

import com.opensymphony.xwork2.ActionSupport;

public class GetXmlInfo extends ActionSupport {
   private String name;
   
	public String getName() {
	return name;
    }

	public void setName(String name) {
		this.name = name;
	}

	public String execute() throws Exception {
		Person person=new Person();
		person.setId(1);
		person.setName("張三s");
		person.setAge(20);
		person.setAdderss("dddddd");
		
		Person person2=new Person();
		person2.setId(2);
		person2.setName("劉備s");
		person2.setAge(50);
		person2.setAdderss("aaaaa");
		
		//構造一個xml
		Document docment=DocumentHelper.createDocument();
		docment.setName("myXml");
		//代表根元素
		 Element root=docment.addElement("users");
		
		root.addComment("is a comment");
		Element userElement= root.addElement("user");
		Element id=userElement.addElement("id");
		Element name=userElement.addElement("name");
		Element age=userElement.addElement("age");
		Element adderss=userElement.addElement("adderss");
		
		
		if("劉備".equals(this.name)){
			id.setText(person2.getId()+"");
			name.setText(person2.getName());
			age.setText(person2.getAge()+"");
			adderss.setText(person2.getAdderss());
				
			}
		
		if("張三".equals(this.name)){
			System.out.println("進來了:"+this.name);
			id.setText(person.getId()+"");
			name.setText(person.getName());
			age.setText(person.getAge()+"");
			adderss.setText(person.getAdderss());
				
			}
		
		HttpServletResponse response=ServletActionContext.getResponse();
		//response.setContentType("text/html; charset=utf-8");
		response.setContentType("text/xml; charset=utf-8");
		//去除快取
		response.setHeader("Cache-Control","no-cache");
		
		PrintWriter out=response.getWriter();
		
		OutputFormat format=OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		
		
		//把xml檔案寫入到out物件中 格式為format
		XMLWriter write=new XMLWriter(out,format);
		write.write(docment);
		
		//out.print(this.name);
		System.out.println("GetXmlInf:"+docment+"\nname:"+this.name);
		
		out.flush();
		out.close();
		return null;
	}
}

json 效果圖:


json jsp程式碼:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>My JSP 'xmlTest.jsp' starting page</title>
    <script type="text/javascript" src="jquery/jquery-1.9.1.js">
    
    </script>
    <script type="text/javascript">
    function getInfo()
    { alert($("#name").val());
    $.post("getJsonInfo.action", 
    { name:$("#name").val()},
    function(returnedDatas,status){ 
    if("success"==status) { 
    var name=returnedDatas.name;
    var adderss=returnedDatas.myAdderss;
    var age=returnedDatas.age;
    var id=returnedDatas.id;
    
   
    
     var htmls="<table width='980px' border='1' align='center'><tr> <td>id</td><th>name</th><th>age</th><th>adderss</th></tr><tr>"
     +"<td>"+id+"</td><td>"+name+"</td><td>"+age+"</td><td>"+adderss+"</td></tr></table>";
     $("body table:eq(0)").remove();
     $("#theBody").append(htmls);
     // alert(name+"/"+adderss);
    //alert(returnedDatas);
    }
    }
    );
    }
    </script>

  </head>
  
  <body id="theBody">
    <select id="name">
     <option>劉備</option>
     <option>張三</option>
   </select>
   
   <input type="button" value="獲取資訊" onclick="getInfo()"/>
  </body>
</html>

jsp action 程式碼:

package accp.struts.json;

import java.util.Date;

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

import com.opensymphony.xwork2.ActionSupport;

public class GetJsonInfo extends ActionSupport {
	private String name;
	private int id;
	private int age;
	private String adderss;
	private Date date;
	private Person person=new Person();
	
	
	
	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	@JSON(format="yyyy-MM-dd",name="myDate",serialize=false)
	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@JSON(serialize=false)//禁止獲取這個欄位
	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;
	}

	@JSON(name="myAdderss")//別名 在解悉的時候 要獲取這個屬性的名字
	public String getAdderss() {
		return adderss;
	}

	public void setAdderss(String adderss) {
		this.adderss = adderss;
	}

	
	public String execute() throws Exception {
		
		Person person=new Person();
		person.setId(1);
		person.setName("張三s");
		person.setAge(20);
		person.setAdderss("dddddd");
		person.setDate(new Date());
		
		
		
		Person person2=new Person();
		person2.setId(2);
		person2.setName("劉備s");
		person2.setAge(50);
		person2.setAdderss("aaaaa");
		person2.setDate(new Date());
		
		
		if("張三".equals(this.name)){
			this.id=person.getId();
			this.age=person.getAge();
			//this.name=person.getName();
			this.adderss=person.getAdderss();
			this.date=person.getDate();
			
		}
		
		if("劉備".equals(this.name)){
			this.id=person2.getId();
			this.age=person2.getAge();
			//this.name=person2.getName();
		   this.adderss=person2.getAdderss();
		   this.date=person2.getDate();
		}
		
		
		System.out.println("OK完畢!"+this.name);
		return SUCCESS;
	}
	

}

功能最強大的 gosn  效果圖:


gosn  jsp頁面程式碼:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
 <title>My JSP 'gsonTest.jsp' starting page</title>
    
 <script type="text/javascript" src="jquery/jquery-1.9.1.js">
    
    </script>
    <script type="text/javascript">
    function getInfo()
    {
       $.post(
       "gsonAction.action", 
       {name:$("#name").val()},
	   function(returnedDatas,status)
	   { 
	     if("success"==status) { 
	     //var obj="{name:'zhangsan',n:'lishi'}";
	     //json物件需轉換才能讀取 //將returndates轉換為Gson物件
	     //var JsonObj=eval("("+obj+")");
	     //alert(JsonObj.name+JsonObj.n);
	     
	     //var objs={age:"age:20"}
	    // alert(objs.age);
	   
	    //var objAction=eval("("+returnedDatas+")");
	    //alert(objAction[0].name);
	    alert("姓名:"+returnedDatas[0].name+",家園地址:"+returnedDatas[0].adderss.homeAdders);
	     
	    
	    var htmls="<table width='980px' border='1' align='center'><tr> <td>id</td><th>name</th><th>公司地址</th><th>家庭adderss</th><th>朋友</th></tr>";
	      
	      
	   
	   for(var i=0;i<returnedDatas.length;i++){
	   var JsonNode=returnedDatas[i];
	   htmls+="<tr><td>"+JsonNode.id+"</td><td>"+JsonNode.name
	   +"</td><td>"+JsonNode.adderss.comanyAdders
	   +"</td><td>"+JsonNode.adderss.homeAdders+"</td><td>"
	   +JsonNode.list[0].name+",\t"+JsonNode.list[1].name+"</td></tr>";
	   }
	   htmls+="</table>";
	   
	   $("body table:eq(0)").remove();
	   $("#theBody").append(htmls);
	      
	   }
	   }
       );
    }
    </script>

  </head>
  
  <body id="theBody">
    <select id="name">
     <option>吳用</option>
     <option>宋江</option>
   </select>
   
   <input type="button" value="獲取all資訊" onclick="getInfo()"/>
   
   
  </body>
</html>

gson action 程式碼:

package accp.struts.json;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;

public class GetGsonAction extends ActionSupport {
	
	private String name;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String execute() throws Exception {
		
	
	
/*------------------構造朋友物件---------------------------------*/	
	//朋友1
	PeoPle people11=new PeoPle();
	people11.setId(2);
	people11.setName("林沖");
	Adderss adderss11=new Adderss();
	adderss11.setHomeAdders("梁山坡衝11");
	adderss11.setComanyAdders("朝廷衝11");
	people11.setAdderss(adderss11);
	
	//朋友2
	PeoPle people12=new PeoPle();
	people12.setId(3);
	people12.setName("武松");
	Adderss adderss12=new Adderss();
	adderss12.setHomeAdders("梁山坡鬆12");
	adderss12.setComanyAdders("朝廷鬆12");
	people12.setAdderss(adderss12);
	
	//朋友3
	PeoPle people13=new PeoPle();
	people13.setId(4);
	people13.setName("李逵");
	Adderss adderss13=new Adderss();
	adderss13.setHomeAdders("梁山坡 李逵8號");
	adderss13.setComanyAdders("朝廷 99號");
	people13.setAdderss(adderss13);
	
	
/*---------------------------------------------------*/
	
	/**
	 * 資訊列表 集合
	 */
    List<PeoPle> listObj=new ArrayList<PeoPle>();
    
    /**
	 * 吳用的個人資訊
	 */
    if(this.name.equals("吳用")){
		PeoPle people1=new PeoPle();
		people1.setId(1);
		people1.setName("吳用");
		//地址
		Adderss adderss=new Adderss();
		adderss.setHomeAdders("梁山坡");
		adderss.setComanyAdders("朝廷");
		people1.setAdderss(adderss);
		
		//朋友列表 集合構造
		List<PeoPle> list=new ArrayList<PeoPle>();
		list.add(people11);
		list.add(people12);
		
		//吳用新增 朋友列表
		people1.setList(list);
		
		//個人資訊列表加入
		listObj.add(people1); //吳用
	}
	
  /**
   * 宋江個人資訊	
   */
  
  if(this.name.equals("宋江")){
	  
	PeoPle people2=new PeoPle();
	people2.setId(20);
	people2.setName("宋江");
	//地址
	Adderss adderss2=new Adderss();
	adderss2.setHomeAdders("梁山坡江");
	adderss2.setComanyAdders("朝廷江");
	people2.setAdderss(adderss2);
	
	//朋友列表集合構建
	List<PeoPle> list2=new ArrayList<PeoPle>();
	list2.add(people11);
	list2.add(people13);
	
	//朋友列表加入 
	people2.setList(list2);
	
	//個人資訊列表加入
	listObj.add(people2); //宋江
	
  }
	
	
	/*
	 * 把資訊轉換為gson物件
	 */
	Gson gson=new Gson();
	String GsonResult=gson.toJson(listObj);
	
	
	//返回客戶端
	HttpServletResponse response=ServletActionContext.getResponse();
	response.setHeader("Cache-Control", "no-cache");//去除快取
	response.setContentType("application/json;charset=utf-8");
	//response.setContentType("text/plain;charset=utf-8");//純文字
	//response.setContentType("text/json;charset=utf-8");
	
	PrintWriter out=response.getWriter();
	out.write(GsonResult); //寫入PrintWriter物件,反回客戶端
	out.flush();
	out.close();
	
	System.out.println("GsonResult:"+GsonResult);
	return null;
	}

}

需要的物件類 程式碼:

人類:

package accp.struts.json;

import java.util.List;

public class PeoPle {
	private int id;
	private String name;
	private Adderss adderss;
	private List<PeoPle> list; //朋友列表
	
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Adderss getAdderss() {
		return adderss;
	}
	public void setAdderss(Adderss adderss) {
		this.adderss = adderss;
	}
	public List<PeoPle> getList() {
		return list;
	}
	public void setList(List<PeoPle> list) {
		this.list = list;
	}
	
}

地址類:

package accp.struts.json;

public class Adderss {
	private String homeAdders;
	private String comanyAdders;
	
	
	public String getHomeAdders() {
		return homeAdders;
	}
	public void setHomeAdders(String homeAdders) {
		this.homeAdders = homeAdders;
	}
	public String getComanyAdders() {
		return comanyAdders;
	}
	public void setComanyAdders(String comanyAdders) {
		this.comanyAdders = comanyAdders;
	}

}

OK!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!這個gson演示的時候有點頭暈,就是人有朋友,朋友也是人類,有點饒

相關文章