首页 > 代码库 > (四)XML基础(客户端和服务端发送与接收xml数据)

(四)XML基础(客户端和服务端发送与接收xml数据)

案例:

index.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 ‘index.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">
<script type="text/javascript"
    src="<%=path%>/script/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
        
        
        function sendXML(){
            var xmlStr = "<driverInfo>";
    xmlStr = xmlStr + "<driverClassName>com.sqlserver.driver.SQLServerDriver</driverClassName>";
    xmlStr = xmlStr + "<url>jdbc:sqlserver://127.0.0.1:xxx</url>";
    xmlStr = xmlStr + "<username>sa</username>";
    xmlStr = xmlStr + "<password>1</password>";
    xmlStr = xmlStr + "</driverInfo>";
    
        var data={
            "xmlStr":xmlStr
        };
        
        var sendURL="<%=path%>/servlet/xmlSevlet?date=" + new Date() + "";

        jQuery.post(sendURL, data, function(xmlData) {

            //从服务端接收到一个xml对象                 
            var userArray = xmlData.getElementsByTagName("userinfo");
            var optionHTML="";
            for (var i = 0; i < userArray.length; i++) {

                    var userElement=userArray[i];

                    var userid=userElement.getAttribute("userid");
                    var username=userElement.getElementsByTagName("username")[0].firstChild.nodeValue;
                    var age=userElement.getElementsByTagName("age")[0].firstChild.nodeValue;
                    
                    optionHTML=optionHTML+"<option value=http://www.mamicode.com/"+userid+">"+username+"="+age+"</option>";
                    
                    $("#userselect").html(optionHTML);   //改变id为userselect的标签的内容
            }

        }, "xml");

    }
</script>
</head>

<body>
    使用ajax来发送与接收XML的数据

    <input type="button" name="button1" id="button1" value="发送与接收XML"
        onclick="sendXML();" />

    <select id="userselect" style="width: 200px;"></select>
</body>
</html>

XmlServlet.java

package servlet;

import java.io.IOException;
import java.io.PrintWriter;

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

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class XmlSevlet extends HttpServlet {

    /**
     * The doGet method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doPost(request, response);
    }

    /**
     * The doPost method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to
     * post.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取客户端传过来的xml字符串,并解析为xml对象
        String xml_str = request.getParameter("xmlStr");
        try {
            Document document = DocumentHelper.parseText(xml_str);

            Element rootElement = document.getRootElement();

            Element element1 = rootElement.element("driverClassName");
            Element element2 = rootElement.element("url");
            Element element3 = rootElement.element("username");
            Element element4 = rootElement.element("password");

            System.out.println(element1.getText());
            System.out.println(element2.getText());
            System.out.println(element3.getText());
            System.out.println(element4.getText());

        

        } catch (DocumentException e) {
            e.printStackTrace();
        }
        
        
        
        /**
         * 要返回一个XML的字符串。客户端的jQuery接收到之后,会自动将XML的字符串转为XML的文档对象。
         * 因为JQuery。post(,,,"xml") 会把返回的字符串对象转为xml对象
         */

        PrintWriter out = response.getWriter();
        StringBuffer str_xml = new StringBuffer();
        str_xml.append("<root>");
        for (int i = 0; i < 5; i++) {
            str_xml.append("<userinfo userid=\""+i+"\">");
            str_xml.append("<username>用户"+i+"</username>");
            str_xml.append("<age>12</age>");
            str_xml.append("</userinfo>");
        }
        str_xml.append("</root>");
        out.print(str_xml.toString());
        System.out.println(str_xml.toString());
        out.flush();
        out.close();

    }

}

结果:

技术分享

技术分享

 

 



 

 本章所有代码都在:  链接

 

(四)XML基础(客户端和服务端发送与接收xml数据)