XMLHTTP First Experience

Source: Internet
Author: User
Tags gettext return string client tomcat
Xml

It's been a long time since I've studied new technology. As a programmer, I feel very ashamed. I've been wanting to see the technology about XMLHTTP, and today I have a little time to do a first experience. fell in love with it at once.
XMLHTTP technology is a good choice if you want to interact with the background data without refreshing the page, or exchange data between heterogeneous systems.
Below is a very small experience of my program, referring to the csdn netizen S_phoenix () to the person's reply.
Start by building a Tomcat Web project.

1:-------index.htm The contents of the document are as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<meta name= "generator" content= "EditPlus" >
<meta name= "Author" content= "" >
<meta name= "Keywords" content= "" >
<meta name= "Description" content= "" >
</HEAD>

<BODY>
<script language= "JavaScript" >
var xml= "<root><test> Li Chunlei </test><test> Mao Zedong </test></root>"
var xmlHttp = new ActiveXObject ("Msxml2.xmlhttp");
var xmldoc=new activexobject ("msxml2.domdocument");
function test () {//Client XML parsing
Xmldoc.loadxml (XML);
if (xmldoc.parseerror.line>0) {
Throw XmlDoc.parseError.reason;
}
var nodes= xmldoc.selectnodes ("/root/test");
for (Var i=0;i<nodes.length;i++) {
Alert (Nodes.item (i). text);
}
}

function action () {//client and server-side communication
Xmlhttp.open ("Post", "Http://127.0.0.1:8888/xmlhttpTest/UrlTestServlet", false);
Xmlhttp.setrequestheader ("Context-type", "text/xml;charset=utf-8");
Xmlhttp.send (XML);
var Showstr=xmlhttp.responsetext;
alert (SHOWSTR);
}

</script>
<button > View the xml</button><br/> that will be transferred
<button > sends XML to server and receives server response </button>
</BODY>
</HTML>


2:------------Write a Servlet:UrlTestServlet.java

/*
* Date Created 2005-4-7
*
* TODO to change the template for this generated file, go to the
* Windows-Preferences-Java-code styles-code templates
*/
Package COM.LCL;

Import javax.servlet.*;
Import javax.servlet.http.*;
Import java.io.*;
Import java.util.*;
Import org.dom4j.io.*;
Import org.dom4j.*;


/**
* @author LCL
*
* TODO to change the template for this generated type annotation, go to the
* Windows-Preferences-Java-code styles-code templates
*/

public class Urltestservlet extends HttpServlet {
private static final String Content_Type = "Text/xml;charset=utf-8";
Initialize Global Variables
public void Init () throws Servletexception {
}
Process the HTTP GET request


public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
Response.setcontenttype (Content_Type);
Request.setcharacterencoding ("Utf-8");
PrintWriter out = Response.getwriter ();
InputStream Is=request.getinputstream ();

Saxreader reader=new Saxreader ();
Document Doc=null;
try{
Doc=reader.read (IS);
catch (Exception ex) {
System.out.println (ex);
}
String[] s= getelementtexts (doc, "Test");
OUT.PRINTLN ("Data exchange success: Return" + s[0] + s[1]);
}

public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
Doget (Request,response);
}

Private String Getelementtext (Document doc,string name) {
Return doc.getrootelement (). Element (name). GetText ();
}

Private string[] Getelementtexts (Document doc,string name) {
List l=doc.getrootelement (). elements (name);
Iterator It=l.iterator ();
List l1=new LinkedList ();
while (It.hasnext ()) {
Element e= (Element) It.next ();
L1.add (E.gettext ());
}
Return (string[]) L1.toarray (new string[]{});
}

Clean up resources
public void Destroy () {
}
}

3:--------Web.xml changes as follows (plus servlet mapping):

<?xml version= "1.0" encoding= "Iso-8859-1"?>

<! DOCTYPE Web-app
Public "-//sun Microsystems, INC.//DTD Web application 2.3//en"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>


<!--jspc servlet mappings Start-->

<servlet>
<servlet-name>UrlTestServlet</servlet-name>
<servlet-class>com.lcl.UrlTestServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>UrlTestServlet</servlet-name>
<url-pattern>/UrlTestServlet</url-pattern>
</servlet-mapping>


<!--jspc servlet mappings End-->
<welcome-file-list>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
</web-app>

Okay, start tomcat, Access: http://127.0.0.1:8888/xmlhttpTest/work/(if your tomcat port is 8080, change it)
See the results, it's really good. Do not refresh the page, let the HTM foreground page and background for a data exchange.

You can even exchange data between different servers, such as a mis system, and a GIS system, to integrate into a system, we used a frame, the left is MIS, the right is a GIS, Exchange data between two systems via JavaScript. If you use XMLHTTP technology, there is absolutely no need to do so.



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.