ajax02基于xml的实现

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

1.创建动态web工程

2.编写model类,提供一个无参的构造方法和一个唯一的标识属性,为每个属性提供一个setter和getter的方法

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() {
	}
}


3.编写PersonServlet类,让这个类继承HttpServlet,并重写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;

public class PersonServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Map<Integer,List<Person>> persons = new HashMap<Integer,List<Person>>();
       
    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);
    }

	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
		doPost(request,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>");
		//6、通过out写回去
		out.write(px.toString());
	}

}
4.配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee                       http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">


 <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-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>  
访问http://localhost:8080/ajax02/person.do?did=1会出现
<persons><person><id>1</id><name>张三</name><salary>1200.0</salary><age>22</age></person><person><id>2</id><name>李四</name><salary>1300.0</salary><age>23</age></person><person><id>3</id><name>王五</name><salary>1400.0</salary><age>24</age></person></persons>
5.编写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>

尝试访问一下http://localhost:8080/ajax02/personXml.html。

这就是后台把数据转换成xml格式传到前台并解析的过程。

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

猜你在找的Ajax相关文章