利用Ajax把前端的数据封装成JSON格式发送到服务器端并写成XML格式在服务器的硬盘上

时间:2022-12-02 08:02:41

1.首先要在前端把要发送的东西(这里是一个实例化的car对象)都准备好,利用Ajax发送到服务器端,代码如下:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JSON Example</title>
<script type="text/javascript" src="json.js"></script>
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest() {
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
}
function doJSON() {
    var car = getCarObject();//得到实例化的对象
 //Use the JSON JavaScript library to stringify the Car object
    var carAsJSON = JSON.stringify(car);
    alert("Car object as JSON:\n " + carAsJSON);
//发送到服务器端的时候会去找lib/web,xml下的映射,通过映射来调用对应的servlet
    var url = "hello";
    createXMLHttpRequest();
    xmlHttp.open("POST", url, true);
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.setRequestHeader("Content-Type",
                    "application/x-www-form-urlencoded;");
    xmlHttp.send(carAsJSON);
}
//回调函数
function handleStateChange() {
      alert("xmlHttp.readyState"+xmlHttp.readyState);
    if(xmlHttp.readyState == 4) {
         alert("xmlHttp.status"+xmlHttp.status);
        if(xmlHttp.status == 200) {
            parseResults();
        }
    }
}

function parseResults() {
    var responseDiv = document.getElementById("serverResponse");
    if(responseDiv.hasChildNodes()) {
        responseDiv.removeChild(responseDiv.childNodes[0]);
    }
    var responseText = document.createTextNode(xmlHttp.responseText);
    responseDiv.appendChild(responseText);
}
//实例化car
function getCarObject() {
    return new Car("Dodge", "Coronet R/T", 1968, "yellow");
}
//先要定义一个car类,才能实例化
function Car(make, model, year, color) {
    this.make = make;
    this.model = model;
    this.year = year;
    this.color = color;
}
</script>
</head>
<body>

<form action="#">
    <input type="button" value="Click here to send JSON data to the server" onclick="doJSON();"/>
</form>
<h2>Server Response:</h2>
<div id="serverResponse"></div>
</body>
</html>

2.以上的代码是把数据发送到服务器了,下面服务器要接收,处理发送过来的数据了,通过lib/web.xml来找到处理的对应的servlet,服务器端嘛,肯定要用servlet来处理的
web.xml的映射如下:即通过映射调用JSONExample这个servlet来处理

 <servlet>
    <servlet-name>JSONExample</servlet-name>
    <servlet-class>JSONExample</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>JSONExample</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>

3.要使JSONExample能工作还需要导入如下包:
利用Ajax把前端的数据封装成JSON格式发送到服务器端并写成XML格式在服务器的硬盘上

4. 请求到来后先调用doPost方法,用readJSONStringFromRequestBody获得发送过来的字符串,再把字符串变为json对象jsonObject = new JSONObject(json),

然后调用writeXMLFile("C:\\hello.xml")来建立xml文档并写到C盘上一个叫做hello.xml的xml的格式的文件(自动生成的,不用自己创建,如果C盘本来就有这个相同的文件名在,则会删掉里面原来的内容并更新新的内容)

import java.io.*;
import java.net.*;
import java.text.ParseException;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.crimson.tree.XmlDocument;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.json.JSONException;
import org.json.JSONObject;


public class JSONExample extends HttpServlet {
    private static final long serialVersionUID = 1L;
    JSONObject jsonObject = null;
    
    public JSONExample() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void writeXMLFile(String outFile) throws Exception
{
//为解析XML作准备,创建DocumentBuilderFactory实例,指定DocumentBuilder
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                               DocumentBuilder db = null;
        try {
        db = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException pce) {
                System.err.println(pce);
                System.exit(1);
        }

        Document doc = null;
        doc = db.newDocument();
//下面是建立XML文档内容的过程,建立根节点car
Element root = doc.createElement("car");
//把car这个根节点放到doc里面去
doc.appendChild(root);
//建立一个节点叫make,其中element1 表示这是root下面的第一个节    
Element element1 = doc.createElement("make");
//把节点名为make的这个节点插入到root这个根节点后面
 root.appendChild(element1 );
//获得make这个节点的具体内容
Text tName = doc.createTextNode(jsonObject.getString("make"));
//把make这个节点的具体内容插入到节点名为make的下面
 element1 .appendChild(tName);
//创建第二个节点
Element element2= doc.createElement("model");
//把第二个节点插入到root后面和第一个节点是兄弟关系
 root.appendChild(element2);
Text tAge = doc.createTextNode(jsonObject.getString("model"));
element2.appendChild(tAge);
//把第三个节点插入到root后面和第一个节点是兄弟关系
Element element3= doc.createElement("year");
root.appendChild(element3);
Text tPhone = doc.createTextNode(jsonObject.getString("year"));
element3.appendChild(tPhone);
//把第四个节点插入到root后面和第一个节点是兄弟关系
Element element4= doc.createElement("color");
root.appendChild(element4);
Text tColor = doc.createTextNode(jsonObject.getString("color"));
element4.appendChild(tColor);
    System.out.println(2);
        //把XML文档输出到指定的文件
FileOutputStream outStream = new FileOutputStream(outFile);
OutputStreamWriter outWriter = new OutputStreamWriter(outStream);
((XmlDocument) doc).write(outWriter, "GB2312");
        outWriter.close();
        outStream.close(); 
    }
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }
    private String readJSONStringFromRequestBody(HttpServletRequest request){
        StringBuffer json = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while((line = reader.readLine()) != null) {
                json.append(line);
            }
        }
        catch(Exception e) {
            System.out.println("Error reading JSON string: " + e.toString());
        }
        return json.toString();
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           String json = readJSONStringFromRequestBody(request);
            //Use the JSON-Java binding library to create a JSON object in Java
            
            try {
                jsonObject = new JSONObject(json);
                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //----------------------------------
            System.out.println(3);
          try {
              System.out.println(4);
            writeXMLFile("C:\\hello.xml");
            System.out.println(5);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}