Você está na página 1de 5

Sample AJAX using jsp

This is a simple ajax example using jsps. In this example, ajax call is described using two jsps ajax1.jsp and ajax2.jsp. In ajax1.jsp, on an event of onkeyup on the text area, it makes an asynchrnous call to ajax2.jsp, where it returns the content in the text area. ajax1.jsp receives the value and dispays it in the div tag.

ajax1.jsp
HTML> <head> <script type="text/javascript"> var req; function ajaxCall() { var poststr = "username=" + encodeURI(document.frmtest.content.value); var url = "ajax2.jsp"; if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); } req.open("POST", url, true); req.onreadystatechange = callback; req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); req.setRequestHeader("Content-length", poststr.length); req.setRequestHeader("Connection", "close"); req.send(poststr); } function callback() { if (req.readyState == 4) { if (req.status == 200) { // update the HTML DOM based on whether or not message is valid parseMessage(); } } } function parseMessage() { var message = req.responseText; setMessage(message); } function setMessage(message) { mdiv = document.getElementById("Message"); mdiv.innerHTML = "<div style=\"color:green\">"+message+"</ div>"; } </script>

</head> <body> <form action="" name="frmtest"> <textarea name="content" rows="3" cols="40" onkeyup="javascript:ajaxCall();"></textarea> </form> <div id="Message"></div> </body> </html>

ajax2.jsp
<% String content = request.getParameter("content"); response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write(content); %>

Example ::: 2

Updating the First and Last name Values


Now let's add the code that makes the round trip to the server. We first specify the URL for the server-side script to be getCustomerInfo.jsp?customerID= . This URL will then have the Customer ID Code appended to it so that the Customer ID is passed as an HTTP GET parameter named param. This means that if a user types in the Customer ID 17534, the resulting URL would be getCustomerInfo.jsp?customerID=17534. Before we send the HTTP request, we specify the onreadystatechange property to be the name of our new function handleHttpResponse(). This means that every time the HTTP ready state has changed, our function handleHttpResponse() is called. Our new function handleHttpResponse() sits there waiting to be called and when it does get called, it checks to see if the readState is equal to 4. If it is equal to 4 and the status is 200, the

request is complete. Since the request is complete, we obtain the response text (responseText), unpack it, and set the first and last name form fields to the returned values. (More readyState info
found here.) <!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>Customer ID to First and Last Name using XmlHttpRequest</title> <script language="javascript" type="text/javascript">

var url = "getCustomerInfo.jsp?customerID="; // The server-side script var http = getHTTPObject(); // We create the XMLHTTPRequest Object function updateFirstLastName() { //alert("updateFirstNameLastName"); var customerIDValue = document.getElementById("customerID").value; http.open("GET", url + escape(customerIDValue), true); http.onreadystatechange = handleHttpResponse; http.send(null); } function handleHttpResponse() { if (http.readyState == 4) { if (http.status == 200) { //alert("handleHTTPResponse"); // Split the comma delimited response into an array. //For plain text response (not XML formatted), //results=http.responseText.split(","); // Or for XML formatted response text: var message=http.responseXML.getElementsByTagName("message")[0]; results = message.childNodes[0].nodeValue.split(","); document.getElementById('firstname').value = results[0]; document.getElementById('lastname').value = results[1]; } else { alert ( "Not able to retrieve name" ); } }

} function getHTTPObject() { var xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else if (window.ActiveXObject) { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } return xmlhttp; }
</script> </head> <body> <form action="post"> <p> Customer ID: <input type="text" size="10" name="customer ID" id="customerID" onblur="updateFirstLastName();" /> </p> First Name: <input type="text" size="10" name="First Name" id="firstname" /> Last Name: <input type="text" size="10" name="Last Name" id="lastname" /> </form> </body> </html>

Program the Server Side


Lets now create a JSP file named getCustomerInfo.jsp. All this file does is return "John, Doe" as the first name last name. This means that anytime the focus leaves the Customer ID field, the first and last name will be automatically set to John, Doe. In fact, this script sends the following XML document to the browser: <message>John,Doe</message>

More complex usages may require DOM, JAXP, SAX or other XML APIs to generate the response.
<% String customerID = request.getParameter("customerID"); if(customerID != null) { //System.out.println("before sending response"); response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); // for plain text response: //response.getWriter().write("John,Doe"); // Or for XML formatted response: response.getWriter().write("<message>John,Doe</message>"); //System.out.println("after sending response"); } else { //nothing to show response.setStatus(HttpServletResponse.SC_NO_CONTENT); } %>

You know by now how to augment the fuctionality of the JSP so that it queries the database for the given Customer ID and returns the corresponding values.

Você também pode gostar