Ajax basics-Chapter 6 (6)

Source: Internet
Author: User
Document directory
  • Bytearrayinputstream

Request Parameters are sent as XML: 

In the createxml method, why is there a backslash before the ending mark?

A backslash can be used to prevent the string from being parsed and marked. Even if most browsers do not have a backslash, The backslash can also be used. However, a backslash should be used according to the standard.

If XMLHTTP. Status = 404 is displayed, the configured servlet cannot be found. It may be because the mapping path is incorrect.

<Select id = "pettypes" size = "6" multiple = "true">

Multiple indicates that multiple values can be selected. You do not need to pay the value for writing.

(1) Get the factory instance of the DOM parser

Documentbuilderfactory. newinstance ()

(2) Get the DOM parser from the DOM Factory

Documentbuilder dombuilder = domfac. newdocumentbuilder ();

(3) convert the XML document to be parsed into an input stream so that the DOM parser can parse it

Documentbuilderfactory. newinstance (). newdocumentbuilder ()
. Parse (New bytearrayinputstream (XML. getbytes ()));

Bytearrayinputstream
public ByteArrayInputStream(byte[] buf)
Create ByteArrayInputStream, Use bufAs its buffer Array
Public byte [] getbytes ()
Use the default Character Set of the platform StringDecodes the data into a byte sequence and stores the results in a new byte array.

Example: postingxml.html

<! Doctype HTML public "-// W3C // dtd xhtml 1.0 strict // en"
Http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd>
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> sending an XML request </title>

<SCRIPT type = "text/JavaScript">

VaR XMLHTTP;

Function createxmlhttprequest (){
If (window. activexobject ){
XMLHTTP = new activexobject ("Microsoft. XMLHTTP ");
}
Else if (window. XMLHttpRequest ){
XMLHTTP = new XMLHttpRequest ();
}
}

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;
}

Function sendpettypes (){
Createxmlhttprequest ();

VaR xml = createxml ();
VaR url = "postingxmlexample? Timestamp = "+ new date (). gettime ();

XMLHTTP. Open ("Post", URL, true );
XMLHTTP. onreadystatechange = handlestatechange;
XMLHTTP. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");
XMLHTTP. Send (XML );
}

Function handlestatechange (){

If (XMLHTTP. readystate = 4 ){
Alert (XMLHTTP. status );
If (XMLHTTP. Status = 200 ){
Alert ("");
Parseresults ();
}
}
}

Function parseresults (){
Alert ("");
VaR responsediv = Document. getelementbyid ("serverresponse ");
If (responsediv. haschildnodes ()){
Responsediv. removechild (responsediv. childnodes [0]);
}

VaR responsetext = Document. createtextnode (XMLHTTP. responsetext );
Responsediv. appendchild (responsetext );
}

</SCRIPT>
</Head>

<Body>
<H1> select the types of pets in your home:
<Form action = "#">
<Select id = "pettypes" size = "6" multiple = "true">
<Option value = "Cats"> cats </option>
<Option value = "dogs"> dogs </option>
<Option value = "fish"> fish </option>
<Option value = "Birds"> birds </option>
<Option value = "hamsters"> hamsters </option>
<Option value = "rabbits"> rabbits </option>
</SELECT>

<Br/>
<Input type = "button" value = "Submit pets" onclick = "sendpettypes ();"/>
</Form>

<H2> Server Response: </H2>

<Div id = "serverresponse"> </div>

</Body>
</Html>

Postingxmlexample. Java:

Package ajaxbook. chap3;

Import java. Io .*;
Import javax. servlet .*;
Import javax. servlet. http .*;
Import javax. xml. parsers. documentbuilderfactory;
Import javax. xml. parsers. parserconfigurationexception;
Import org. W3C. Dom. Document;
Import org. W3C. Dom. nodelist;
Import org. xml. Sax. saxexception;

Public class postingxmlexample extends httpservlet {

Protected void dopost (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception {

String xml = readxmlfromrequestbody (request );
Document xmldoc = NULL;
Try {
Xmldoc =
Documentbuilderfactory. newinstance (). newdocumentbuilder ()
. Parse (New bytearrayinputstream (XML. getbytes ()));
}
Catch (parserconfigurationexception e ){
System. Out. println ("parserconfigurationexception:" + E );
}
Catch (saxexception e ){
System. Out. println ("saxexception:" + E );
}

/* Note how the JAVA Implementation of the W3C Dom has the same methods
* As the Javascript implementation, such as getelementsbytagname and
* Getnodevalue.
*/
Nodelist selectedpettypes = xmldoc. getelementsbytagname ("type ");
String type = NULL;
String responsetext = "selected pets :";
For (INT I = 0; I <selectedpettypes. getlength (); I ++ ){
Type = selectedpettypes. Item (I). getfirstchild (). getnodevalue ();
Responsetext = responsetext + "" + type;
}

Response. setcontenttype ("text/XML ");
Response. getwriter (). Print (responsetext );
}

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 e ){
System. Out. println ("error reading XML:" + E. tostring ());
}
Return XML. tostring ();
}
}
Note:

1. servlet
Response implements the httpservletresponse interface, and request implements the httpservletrequest interface.

1. There are two output streams:
Byte output: Response. getoutputstream ()
Character Form output: Response. getwriter ()

2. There are two input streams:
Byte input: request. getinputstream ()
Character format input: request. getreader ()

Ii. jsp
The response object in JSP has implemented the httpservletresponse interface, and the request object has implemented the httpservletrequest interface.

1. output stream
The out object in JSP is response. the returned value of getoutputstream (). Therefore, you cannot call response in JSP. getoutputstream () method. Otherwise, a duplicate call error occurs, because two identical byte output streams cannot be created at the same time.
In JSP, you can use the response. getwriter () method to create a character output stream to output character data to the web page.

2. input stream
JSP does not seem to automatically implement the input stream object, so you can use the request. getinputstream (), request. getreader () method to create the input stream.

3. Read and Write files on the server
The file. Reader () and file. Writer () methods can be used to read and write files anywhere on the server.
The application (servletcontext). getresourceasstream () method can read files in the servlet context.

Related Article

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.