Here below is a basic AJAX call with XMLHttpRequest and Java Servlet. Tested with IE6.0 and FireFox3.0. I try to use the MVC (Model-View-Controller) for this demo.
2. Create a controller class.
| HelloWorld.java: |
|
package mvc.demo;
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;
public class HelloResponse extends HttpServlet {
private static final String CONTENT_TYPE = "text/xml; charset=UTF-8"; //Process the HTTP Get request public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user = request.getParameter("name1"); String hello; HelloWorld helloWorld = new HelloWorld(); if ((user == null) || (user.equals(""))) hello = helloWorld.sayHello(); else hello = helloWorld.sayHello(user);
response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); request.setAttribute("result", hello); out.println(hello); out.close(); } }
|
4. Create a view (HTML page).
| index.html: |
|
<script>
var xmlhttp=null; var XMLHttpFactories = [ function () {return new XMLHttpRequest()}, function () {return new ActiveXObject("Msxml2.XMLHTTP")}, function () {return new ActiveXObject("Msxml3.XMLHTTP")}, function () {return new ActiveXObject("Microsoft.XMLHTTP")} ];
function createXMLHTTPObject() { var xmlhttp = false; for (var i=0;i<XMLHttpFactories.length;i++) { try { xmlhttp = XMLHttpFactories[i](); } catch (e) { continue; } break; } return xmlhttp; }
function GetMessage() { var url = "/helloWorld/sayHello"; // This is a Java servlet, can be any web url like php/asp/jsp xmlhttp = null; xmlhttp = createXMLHTTPObject(); if (xmlhttp != null) { xmlhttp.onreadystatechange = onResponseMessage; xmlhttp.open("GET", url, true); xmlhttp.send(null); } else { alert("Your browser does not support XMLHTTP."); } }
function onResponseMessage() { if(xmlhttp.readyState!=4) return; if(xmlhttp.status!=200) { alert("Problem retrieving car XML data"); return; } document.getElementById("show_txt").innerHTML=xmlhttp.responseText; }
</script>
<body onload="GetMessage()">
<table bgcolor="#6699CC" cellpadding="0" cellspacing="0" border="0"> <tr><td> <table bgcolor="#6699CC" cellpadding="3" cellspacing="1" border="0" width="100%"> <tr bgcolor="#6699CC"> <td width="100%"> <div align="center"><font color="#ffffff"> <b> Information </b> </font></div> </td> </tr>
<tr bgcolor="#eeeeee"> <td> <div id="show_txt"></div> </td> </tr> </table> </td></tr></table>
</body>
|
Note: sayHello is a Java servlet that return the message "Hello World". It could be any web url like php/asp/jsp that return the message.