ajax04 xstream的讲解

前端之家收集整理的这篇文章主要介绍了ajax04 xstream的讲解前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

xStream可以轻易的将Java对象和xml文档相互转换,而且可以修改某个特定的属性和节点名称,而且也支持json的转换;

1.建立动态web工程。

2.编写model类。

package org.itat.zttc.model;


public class Person {
	private int id;
	private String name;
	private double salary;
	private int age;
	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 double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Person(int id,String name,double salary,int age) {
		super();
		this.id = id;
		this.name = name;
		this.salary = salary;
		this.age = age;
	}
	
	public Person() {
	}
}

package org.itat.zttc.model;

import java.util.ArrayList;
import java.util.List;

public class Group {
	private int id;
	private String name;
	List<User> users;
	
	public void addUser(User u) {
		if(users==null) {
			users = new ArrayList<User>();
		}
		users.add(u);
	}
	
	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 Group(int id,String name) {
		super();
		this.id = id;
		this.name = name;
	}
	
	public Group() {
	}

}
package org.itat.zttc.model;

public class User {
	private int id;
	private String username;
	private String password;
	private Group group;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public Group getGroup() {
		return group;
	}
	public void setGroup(Group group) {
		this.group = group;
	}
	
	public User() {
	}
	
	public User(int id,String username,String password,Group group) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
		this.group = group;
	}
	
	public User(int id,String password) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
	}
}

3导入xstream的包

4.编写测试类

package org.itat.zttc.test;



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

import org.itat.zttc.model.Group;
import org.itat.zttc.model.Person;
import org.itat.zttc.model.User;
import org.junit.Test;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import com.thoughtworks.xstream.io.json.JsonWriter;

public class TestXstream {

	@Test
	public void test01() {
		//1、创建XStream对象
		XStream stream = new XStream();
		//默认的名称使用的是包的名称可以通过alias改别名
		stream.alias("person",Person.class);
		//改属性名也是可以的,一般不用
		stream.aliasField("username",Person.class,"name");
		//如果希望把某个子节点修改属性也可以,但是更不常用
		stream.useAttributeFor(Person.class,"id");
		//2、创建对象
		Person p = new Person(1,"小武",1900,24);
		//3、完成转换
		String xml = stream.toXML(p);
		//4、输出
		System.out.println(xml);
	}
	
	@Test
	public void test02() {
		XStream stream = new XStream();
		stream.alias("user",User.class);
		stream.alias("group",Group.class);
		User u = new User(1,"劳动法","123",new Group(1,"财务处"));
		System.out.println(stream.toXML(u));
		
	}
	
	@Test
	public void test03() {
		XStream stream = new XStream();
		stream.alias("user",User.class);
		stream.alias("users",List.class);
		List<User> us = new ArrayList<User>();
		User u = new User(1,"财务处"));
		us.add(u);
		us.add(new User(2,"张学友","财务处")));
		us.add(new User(3,"黎明","财务处")));
		us.add(new User(4,"郭富城","物理系")));
		System.out.println(stream.toXML(us));
		
	}
	
	@Test
	public void test04() {
		XStream stream = new XStream();
		stream.alias("user",Group.class);
		Group g = new Group();
		/*
		 * 默认情况在users这个节点中会像封装一个users的父亲节点,然后才封装user
		 * 有些时候可能不需要users可以使用
		 */
		stream.addImplicitCollection(Group.class,"users");
		g.addUser(new User(1,"老张","123"));
		g.addUser(new User(2,"老李","1234"));
		g.addUser(new User(3,"老刘","12345"));
		g.addUser(new User(4,"老王","123456"));
		System.out.println(stream.toXML(g));
	}
	
	@Test
	public void test05() {
		XStream stream = new XStream();
		stream.alias("user",User.class);
		String xml = "<user><id>1</id><username>aaa</username><password>123</password>" +
				"<group><id>1</id><name>财务处</name></group></user>";
		User user = (User)stream.fromXML(xml);
		System.out.println(user.getId()+","+user.getUsername()+","+user.getPassword()+","+user.getGroup().getName());
	}
	
	@Test
	public void test06() {
		XStream stream = new XStream();
		stream.alias("user",List.class);
		List<User> us = (List<User>)stream.fromXML(TestXstream.class.getClassLoader().getResourceAsStream("users.xml"));
		for(User user:us) {
			System.out.println(user.getId()+","+user.getGroup().getName());
		}
	}
	
	@Test
	public void test07() {
		//转换json需要使用Jettison这个包
		XStream stream = new XStream(new JettisonMappedXmlDriver(){
			//通过覆盖以下方法可以有效的删除json根节点
			//一般不使用XStream来转换json,效率不高,效率比较高的Json工具是Jaskson
			@Override
			public HierarchicalStreamWriter createWriter(Writer out) {
				 return new JsonWriter(out,JsonWriter.DROP_ROOT_MODE);
			}
		});
		stream.alias("group",Group.class);
		stream.alias("user",User.class);
		Group g = new Group();
		g.addUser(new User(1,"123456"));
		System.out.println(stream.toXML(g));
	}

}

5.为test06添加测试文件users.xml
<?xml version="1.0" encoding="UTF-8"?>
<users>
  <user>
    <id>1</id>
    <username>劳动法</username>
    <password>123</password>
    <group>
      <id>1</id>
      <name>财务处</name>
    </group>
  </user>
  <user>
    <id>2</id>
    <username>张学友</username>
    <password>123</password>
    <group>
      <id>1</id>
      <name>财务处</name>
    </group>
  </user>
  <user>
    <id>3</id>
    <username>黎明</username>
    <password>123</password>
    <group>
      <id>1</id>
      <name>财务处</name>
    </group>
  </user>
  <user>
    <id>4</id>
    <username>郭富城</username>
    <password>123</password>
    <group>
      <id>1</id>
      <name>物理系</name>
    </group>
  </user>
</users>
7.run as java applet察看一下测试结果吧。。。

8.可以把测试类中的文件编写成工具类,在需要使用时进行调用

package org.itat.zttc.util;


import java.util.Map;
import java.util.Set;

import com.thoughtworks.xstream.XStream;

public class XStreamUtil {
	private static XStreamUtil util;
	private XStreamUtil(){}
	
	public static XStreamUtil getInstacne() {
		if(util==null) util = new XStreamUtil();
		return util;
	}
	
	
	public String obj2xml(Object obj,Map<String,Class<?>> alias) {
		XStream stream = new XStream();
		Set<String> keys = alias.keySet();
		for(String key:keys) {
			stream.alias(key,alias.get(key));
		}
		return stream.toXML(obj);
	}
	
	public Object xml2obj(String xml,alias.get(key));
		}
		return stream.fromXML(xml);
	}
}

9.编写PersonServlet 覆盖doget和dopost方法
package org.itat.zttc.ajax;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.itat.zttc.model.Person;
import org.itat.zttc.util.XStreamUtil;

/**
 * Servlet implementation class PersonServlet
 */
public class PersonServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Map<Integer,List<Person>> persons = new HashMap<Integer,List<Person>>();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PersonServlet() {
        super();
        List<Person> ps = new ArrayList<Person>();
        ps.add(new Person(1,"张三",1200,22));
        ps.add(new Person(2,"李四",1300,23));
        ps.add(new Person(3,"王五",1400,24));
        persons.put(1,ps);
        ps = new ArrayList<Person>();
        ps.add(new Person(11,"刘德华",12000,32));
        ps.add(new Person(12,"周杰伦",13000,33));
        ps.add(new Person(13,"张曼玉",14000,34));
        ps.add(new Person(14,"梁朝伟",15000,35));
        persons.put(2,ps);
        
        ps = new ArrayList<Person>();
        ps.add(new Person(21,"孙悟空",22000,132));
        ps.add(new Person(22,"猪八戒",23000,133));
        ps.add(new Person(23,"沙和尚",24000,134));
        ps.add(new Person(24,"唐和尚",25000,135));
        persons.put(3,ps);
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request,HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request,HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,IOException {
		//1、由于返回的是xml,需要为respose设置contentType
		response.setContentType("text/xml;charset=utf-8");
		//2、获取Writer
		Writer out = response.getWriter();
		//3、获取部门id
		int did = Integer.parseInt(request.getParameter("did"));
		//4、获取用户列表对象,
		List<Person> ps = persons.get(did);
		//5、拼接xml
		/*StringBuffer px = new StringBuffer();
		px.append("<persons>");
		for(Person p:ps) {
			px.append("<person>");
			px.append("<id>").append(p.getId()).append("</id>");
			px.append("<name>").append(p.getName()).append("</name>");
			px.append("<salary>").append(p.getSalary()).append("</salary>");
			px.append("<age>").append(p.getAge()).append("</age>");
			px.append("</person>");
		}
		px.append("</persons>");*/
		Map<String,Class<?>> alias = new HashMap<String,Class<?>>();
		alias.put("persons",List.class);
		alias.put("person",Person.class);
		String xml = XStreamUtil.getInstacne().obj2xml(ps,alias);
		//6、通过out写回去
		out.write(xml);
	}

}

10.配置web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>ajax01</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
 
  <servlet>
    <description></description>
    <display-name>PersonServlet</display-name>
    <servlet-name>PersonServlet</servlet-name>
    <servlet-class>org.itat.zttc.ajax.PersonServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>PersonServlet</servlet-name>
    <url-pattern>/person.do</url-pattern>
  </servlet-mapping>
  
</web-app>
11.编写personXml.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
window.onload = init;
function init() {
	//1、获取部门节点
	var dn = document.getElementById("dep");
	//2、为该节点创建onchange
	dn.onchange = getPerson
	//3、创建一个getPerson的方法来处理事件 
}

function getPerson() {
	var did = this.value;
	//1、获取XMLHttpRequest;
	var xhr = createXMLHttpRequest();
	//2、通过xhr来打开页面,使用POST
	xhr.open("POST","person.do",true);
	xhr.onreadystatechange = function() {
		//3、处理请求
		if(xhr.readyState==4&&xhr.status==200) {
			//3.1、获取xml节点
			var xmlDoc = xhr.responseXML;
			//由于response的contentType是text/xml类型,此时就只能获取节点
			//alert(xhr.resonseText);
			//3.2、获取所有的person节点
			var pns = xmlDoc.getElementsByTagName("person");
			//3.3、遍历所以节点,获取id,name等信息
			var node = "";
			for(var i=0;i<pns.length;i++) {
				node+=getValueByProp(pns[i],"id")+"----------"+
				      getValueByProp(pns[i],"name")+"----------"+
				      getValueByProp(pns[i],"salary")+"----------"+
				      getValueByProp(pns[i],"age")+"<br/>"
			}
			//3.4、写入到persons
			document.getElementById("persons").innerHTML = node;
		}
	}
	xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xhr.send("did="+did);
	//4、发送信息,需要传入did
}
//根据节点获取值
function getValueByProp(node,prop) {
	return (node.getElementsByTagName(prop))[0].firstChild.nodeValue;
}

function createXMLHttpRequest() {
	if(window.XMLHttpRequest) {
		//针对其他主流浏览器
		return new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		//针对IE5和IE6
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		alert("你使用的浏览器不支持XMLHttpRequest,请换一个浏览器再试!");
		return null;
	}
}
</script>
</head>
<body>
<select id="dep">
	<option value="1">普通组</option>
	<option value="2">明星组</option>
	<option value="3">火星组</option>
</select>
<div id="persons"></div>
</body>
</html>

12.在浏览器中访问http://localhost:8080/ajax01/person.do?did=2察看一下测试结果吧。

以上就是xstream的简单使用

原文链接:https://www.f2er.com/ajax/163851.html

猜你在找的Ajax相关文章