Request parameters are sent as XML

Source: Internet
Author: User
Tags return string window stringbuffer
xml| Request business logic: Dropdown box Select the type of pet you like, multiple selections, and select parameters to be constructed into XML parameters to send. The server sends back the response results.

Page: postingxml.html

<%@ page contenttype= "text/html; CHARSET=GBK "%>
<title>
Send an XML request
</title>
<script type= "Text/javascript" >
XMLHttpRequest objects
var xmlHttp;

Creating XMLHttpRequest Objects
function Createxmlhttprequest () {
if (window. ActiveXObject) {
XmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
}
else if (window. XMLHttpRequest) {
XmlHttp = new XMLHttpRequest ();
}
}

Create an XML string
function Createxml () {
var xml = "<pets>"
var options = document.getElementById ("Pettypes"). ChildNodes;
var option = null;
for (var i = 0; i < options.length; i++) {
option = Options[i];
if (option.selected) {
XML = XML + "<type>" + option.value + "<\/type>";
}
}

XML = XML + "<\/pets>";
return XML;
}

Send Pet Type request
function Sendpettypes () {
Createxmlhttprequest ();

var xml = Createxml ();
Processing methods
var url = "postingxmlexample?timestamp=" + New Date (). GetTime ();

Xmlhttp.open ("POST", url,true);
Xmlhttp.onreadystatechange = Handlestatechange;
Set Request Header Format
Xmlhttp.setrequestheader ("Conteyt-type", "application/x-www-form-urlencoded;");
Xmlhttp.send (XML);
}

callback method
function Handlestatechange () {
if (xmlhttp.readystate = = 4) {
if (Xmlhttp.status = = 200) {
Parse return result
Parseresults ();
}
}
}

Parse return result
function Parseresults () {
var responsediv = document.getElementById ("Serverresponse");
if (Responsediv.haschildnodes ()) {
Responsediv.removechild (Responsediv.childnodes[0]);
}
Returns text constructs a text node
var responsetext = document.createTextNode (Xmlhttp.responsetext);
Responsediv.appendchild (ResponseText);
}
</script>
<body bgcolor= "#ffffff" >
Please select the type of pet in your home:
<form action= "#" >
<select id= "Pettypes" size= "6" multiple= "multiple" >
<option value= "Cats" > Cat </option>
<option value= "Dogs" > Dog </option>
<option value= "Fish" > Fishes </option>
<option value= "birds" > Bird </option>
<option value= "Hamsters" > Mouse </option>
<option value= "Rabbits" > Rabbit </option>
</select>

<br/><br/>
<input type= "button" value= "Submit"/>
</form>

<div id= "Serverresponse" >
</div>
</body>

Server-side

Postingxmlexample.java

Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
Import javax.xml.parsers.*;

Import org.w3c.dom.*;

public class Postingxmlexample
Extends HttpServlet {
private static final String Content_Type = "text/html;" CHARSET=GBK ";

Initialize Global Variables
public void Init () throws Servletexception {
}

Process POST Requests
public void DoPost (HttpServletRequest request, httpservletresponse response) throws
Servletexception, IOException {
Get the requested XML string
String XML = readxmlfromrequestbody (request);
Document xmldoc = null;
try {
xmldoc = Documentbuilderfactory.newinstance (). Newdocumentbuilder (). Parse (New Bytearrayinputstream (Xml.getBytes ()) );
}
catch (Exception ex) {
System.out.println ("Parse XML exception ...");
}

Get Type node List
NodeList selectedpettypes = Xmldoc.getelementsbytagname ("type");
String type = null;
String responsetext = "Selected pet is:";
for (int i = 0; i < selectedpettypes.getlength (); i++) {
Type = Selectedpettypes.item (i). Getfirstchild (). Getnodevalue ();
ResponseText = ResponseText + "" + type;
}

Response.setcontenttype (Content_Type);
Response.getwriter (). print (responsetext);
}

/**
* Readxmlfromrequestbody
*
* @param request HttpServletRequest
* @return String
*/
Private String Readxmlfromrequestbody (HttpServletRequest request) {
StringBuffer XML = new StringBuffer ();
String line = null;
try {
BufferedReader reader = Request.getreader ();
while (line = Reader.readline ())!= null) {
Xml.append (line);
}
}
catch (Exception ex) {
SYSTEM.OUT.PRINTLN ("Read XML error:" + ex.getmessage ());
}
return xml.tostring ();
}

Clean up resources
public void Destroy () {
}
}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.