Download presentation
Presentation is loading. Please wait.
1
AJAX and Java Servlet ISYS 350
2
AJAX Asynchronous JavaScript and XML:
JavaScript, Document Object Model, Cascade Style Sheet, XML, server-side script such as JSP, .Net, PHP, etc. Partial refresh: It lets you update part of a web page without having to reload the entire page. RIA: Rich Internet Application Quick response time, interactive page
4
How AJAX Updates a Page When an event happens, JavaScript (AJAX engine) prepares a request and sends it to the web server. The server receives the request and processes it. The server prepares a response and sends it back to the browser. The JavaScript parses the response to update the page.
6
XMLHTTPRequest Javascript object
Update a web page without reloading the page Request data from a server after the page has loaded Receive data from a server after the page has loaded
7
Creating a XMLHttpRequest Object
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
8
The Open Methods of XMLHTTPRequest object
The HTTP and HTTPS requests of the XMLHttpRequest object must be initialized through the open method. There 5 parameters, but 2 are enough: open( Method, URL, Asynchronous, UserName, Password ) Method: GET, POST URL: the URL of the HTTP request Asynchronous: true/false; default is true Example: xmlhttp.open('GET', 'demoJSPAjax.jsp', true);
9
The send method This method accepts a single parameter containing the content to be sent with the request. This parameter may be omitted if no content needs to be sent. send( Data )
10
The onreadystatechange event listener
For an asynchronous request, the onreadystatechange event listener will be automatically invoked for each of the following actions that change the readyState property of the XMLHttpRequest object.
11
The Four ReadyStates After the open method has been invoked successfully, the readyState property of the XMLHttpRequest object should be assigned a value of 1. After the send method has been invoked and the HTTP response headers have been received, the readyState property of the XMLHttpRequest object should be assigned a value of 2. Once the HTTP response content begins to load, the readyState property of the XMLHttpRequest object should be assigned a value of 3. Once the HTTP response content has finished loading, the readyState property of the XMLHttpRequest object should be assigned a value of 4.
12
Example xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4){ alert(xmlhttp.readyState); } }; xmlhttp.open('GET', 'somepage.xml', true); xmlhttp.send(null); Note 1: The listener must be defined before the open method is invoked. The open method must be invoked before the send method is invoked.
13
The responseXML property and responseText
After a successful and completed call to the send method of the XMLHttpRequest, if the server response was valid XML and the Content-Type header sent by the server is understood by the user agent as an Internet media type for XML, the responseXML property of the XMLHttpRequest object will contain a DOM document object. Another property, responseText will contain the response of the server in plain text by a conforming user agent, regardless of whether or not it was understood as XML.
14
Overall Processes Create an XMLHttpRequest object
Create the function to be executed when the server response is ready Send the request off to a file on the server Insert the response from the server to the web page
15
Example: HTML Page <script> function MakeRequest() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.open('GET', ' true); xmlhttp.send(null); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState ==4){ document.getElementById('ResponseDiv').innerHTML = xmlhttp.responseText; } } </script> </head> <body> <input type='button' onclick='MakeRequest();' value='Use AJAX!!!!'/> <div id='ResponseDiv'> This is a div to hold the response. </div> </body>
16
Example: demoJSPAjax.jsp
<body> <% out.println("This is JSP response to your request!"); %> </body>
17
Example: Compute future value Problem using JavaScript: no protection of source code
18
fvForm <form name="fvForm" action="">
Enter PV: <input type="text" id="PV" name="PV" value="" /><br> Select Rate: <select name="Rate" id="Rate"> <option value=0.04>4%</option> <option value=0.045>4.5%</option> <option value=0.05>5%</option> <option value=0.055>5.5%</option> <option value=0.06>6%</option> <option value=0.065>6.5%</option> <option value=0.07>7%</option> </select><br> Select Year: <br> <input type="radio" name="Year" id="Year10" value=10 />10 year<br> <input type="radio" name="Year" id="Year15" value=15 />15 year<br> <input type="radio" name="Year" id="Year30" value=30 />30 year<br> <br> Future Value: <input type="text" id="FV" name="FV" /> <br> <input type="button" value="ComputeFV" name="btnCompute" onClick="computeFV()" /> <br><br> </form>
19
Using AJAX to compute FV
function computeFV(){ myPV=parseFloat(document.getElementById("PV").value); myRate=parseFloat(document.getElementById("Rate").value); if (document.getElementById("Year10").checked) {myYear=10;} else if (document.getElementById("Year15").checked) {myYear=15;} else {myYear=30;} if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4){ document.getElementById("FV").value = xmlhttp.responseText; } }; // xmlhttp.open('GET', 'FVServlet?PV='+ myPV + '&Rate=' + myRate + '&Year=' + myYear , true); xmlhttp.open('GET', 'computeFV.jsp?PV='+ myPV + '&Rate=' + myRate + '&Year=' + myYear , true); xmlhttp.send(null);
20
The computeFV.jsp file body> <% String myPV, myRate, myYear;
myPV=request.getParameter("PV"); myRate=request.getParameter("Rate"); myYear=request.getParameter("Year"); double FV, PV, Rate, Year; PV=Double.parseDouble(myPV); Rate=Double.parseDouble(myRate); Year=Double.parseDouble(myYear); FV=PV*Math.pow(1+Rate,Year); out.println(FV); %> </body>
21
FVServlet.java protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet FVServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet FVServlet at " + request.getContextPath() + "</h1>"); */ String myPV, myRate, myYear,qString; myPV=request.getParameter("PV"); myRate=request.getParameter("Rate"); myYear=request.getParameter("Year"); double FV, PV, Rate, Year; PV=Double.parseDouble(myPV); Rate=Double.parseDouble(myRate); Year=Double.parseDouble(myYear); FV=PV*Math.pow(1+Rate,Year); out.println(FV); out.println("</body>"); out.println("</html>"); }
22
Loan calculation: Server determines rate based on loan, term, credit passed to JSP by AJAX
23
Passing loan, term, credit to Servlet by AJAX and return rate and payment (many values)
<script> function computeLoan(){ loan=parseFloat(document.loanForm.loan.value); term=parseFloat(document.loanForm.term.options[document.loanForm.term.selectedIndex].value); if (document.loanForm.credit[0].checked) {credit="Excellent";} else if (document.loanForm.credit[1].checked) {credit="Good";} else {credit="Fair";} if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState ==4){ returnValArray=xmlhttp.responseText.split(","); document.getElementById('rate').value=returnValArray[0]; document.loanForm.payment.value=returnValArray[1]; } } xmlhttp.open('GET', 'computeLoanAjax?Loan='+ loan + '&Term=' + term + '&Credit=' + credit , true); xmlhttp.send(null); } </script>
24
HTML form <body> Loan Application Form<br><br>
<form name="loanForm"> Enter Loan: <input id='loan' type="text" name="loan" value="" /><br><br> Select Term: <select name="term"> <option value=5>5 years</option> <option value=10>10 years</option> <option value=15>15 years</option> <option value=20>20 years</option> <option value=30>30 years</option> </select><br><br> Select your credit status: <br> <input type="radio" name="credit" value="Excellent" />Excellent<br> <input type="radio" name="credit" value="Good" />Good<br> <input type="radio" name="credit" value="Fair" />Fair<br> <br> Best rate we offer: <input type="text" name="rate" id="rate" /><br><br> Payment: <input type="text" name="payment" id="payment" /><br><br> <input type="button" value="Compute Payment" name="btnCompute" onClick="computeLoan()" /> </form> </body>
25
computeLoanAjax Servlet to compute the loan
double loan,term, rate,payment; String credit; loan=Double.parseDouble(request.getParameter("Loan")); term=Double.parseDouble(request.getParameter("Term")); credit=request.getParameter("Credit"); rate=.04; if (loan> ) rate+=.005; if (term>20)rate+=.005; if (credit=="Excellent") rate-=.005; if (credit=="Fair") rate+=.01; payment=loan*rate/12/(1-Math.pow(1+rate/12,-12*term)); out.print(rate + "," + payment);
26
Create a CID listbox and Use AJAX to retrieve Customer Data: Listbox won’t be recreated repetitively
27
Create a CID listbox and Use AJAX to retrieve Customer Data
<form name="cidForm" method ="post"> Select CID:<select name="mycid" onchange="showData(this.value)"> <% Connection connection = null; String DBUrl="jdbc:derby://localhost:1527/CRM2"; try { String myCid, strSQL; connection = DriverManager.getConnection(DBUrl); Statement SQLStatement = connection.createStatement(); strSQL="select cid from customer"; ResultSet rs = SQLStatement.executeQuery(strSQL); while (rs.next()) { myCid=rs.getString("cid"); out.println("<option value='" +myCid + "'>" + myCid + "</option>"); } } catch(SQLException e) { out.println(e.getMessage()); } %> </select> </form> <br><br> <div id='ResponseDiv'> Name: <input type="text" id="cname" name="cname" value="" /><br><br> City: <input type="text" id ="city" name="city" value="" /><br><br> Rating: <input type="text" id="rating" name="rating" value="" /> </div> Note: This program uses listbox onchange event to pass the selected value, this.value, to procedure.
28
Use AJAX to retrieve Customer Data
<script> function showData(CID) { if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4){ returnValArray=xmlhttp.responseText.split(","); document.getElementById('cname').value=returnValArray[0]; document.getElementById('city').value=returnValArray[1]; document.getElementById('rating').value=returnValArray[2]; } xmlhttp.open('GET', 'getCustAjax?CID=' + CID, true); xmlhttp.send(null); </script>
29
Servlet to return the data
Connection connection = null; String DBUrl="jdbc:derby://localhost:1527/CRM2"; try { String myCid, strSQL, Cname, City, Rating; connection = DriverManager.getConnection(DBUrl); Statement SQLStatement = connection.createStatement(); myCid=request.getParameter("CID"); strSQL="select * from customer where cid='" + myCid + "'"; ResultSet rs = SQLStatement.executeQuery(strSQL); if (rs.next()) Cname=rs.getString("CNAME"); City=rs.getString("CITY"); Rating=rs.getString("Rating"); rs.close(); out.println(Cname + "," + City + "," + Rating); } else out.println("Customer not exist!"); catch(SQLException e) out.println("Something wrong"); out.println(e.getMessage()); Note: This program returns three fields as a string separated by comma so that the JavaScript can use the split function to parse it to an array.
30
Show Customers with Selected Rating
31
Form and Ajax code <script> function showT()
{ if (document.getElementById("A").checked) {rating="A";} else if (document.getElementById("B").checked) {rating="B";} else {rating="C";} if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4){ document.getElementById("fromAjax").innerHTML = xmlhttp.responseText; } xmlhttp.open('GET', 'showCustomer?rating=' + rating, true); xmlhttp.send(null); </script> </head> <body> <form name="newForm"> Select a rating: <br> <input type="radio" name="rating" id="A" value="A" />A<br> <input type="radio" name="rating" id="B" value="B" />B<br> <input type="radio" name="rating" id="C" value="C" />C<br> <input type="button" value="Submit" onclick="showT()" /> </form> Customer Data:<br><br> <div id="fromAjax"></div>
32
Servlet Code Connection connection;
String DBUrl="jdbc:derby://localhost:1527/CRM2"; try { String Cid, strSQL, Cname, City, Rating; connection = DriverManager.getConnection(DBUrl); Statement SQLStatement = connection.createStatement(); String rating; rating=request.getParameter("rating"); strSQL="select * from customer where rating='" + rating + "'"; ResultSet rs = SQLStatement.executeQuery(strSQL); out.println("<table border='1' width='400' cellspacing=1>"); out.println(" <thead><tr>"); out.println("<th>CID</th> <th>Cname</th> <th>City</th> <th>Rating</th>"); out.println("</tr></thead>"); while (rs.next()) { Cid=rs.getString("CID"); Cname=rs.getString("CNAME"); City=rs.getString("CITY"); Rating=rs.getString("Rating"); out.println("<tr>"); out.println("<td>" + Cid + "</td>"); out.println("<td>" + Cname + "</td>"); out.println("<td>" + City + "</td>"); out.println("<td>" + Rating + "</td>"); out.println("</tr>"); } rs.close(); } catch(SQLException e) out.println(e.getMessage()); out.println("</table>");
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.