Mark Beleski
Mark Beleski

Reputation: 55

Simple AJAX Servlet with Callback

I am trying to learn AJAX and now I'm reading up on servlets and callbacks. I feel like my book didn't cover servlets or callbacks in detail so I looked at a number of online resources only to get more confused. I feel like I'll understand it with a hands on example so I'm counting on you guys to help me out :) It will be greatly appreciated! What I want to do is create an index page that accepts a number, passes it to a servlet asynchronously to get squared, and displays the result on the index page. Here is what I got so far.

index.html

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script>
            function setup() {
                if (window.XMLHttpRequest) {
                    r = new XMLHttpRequest();
                } else {
                    r = new ActiveXObject("Microsoft.XMLHTTP");
                }
                r.open("get","convert",true);
                r.onreadystatechange=???????????
                r.send(null);
            }
        </script>
    </head>
<body onload="setup()">
    <h3>Enter a number to be squared <input type="text" name="number" size="2" 
        maxlength="4"/></h3>
    <p id="result"></p>
</body>

Convert.java

package squared;

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;
import java.sql.*;

public class convert extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        response.setContentType("text/xml"); 
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out=response.getWriter();

    }
}

Thank you for taking the time to help me out!

Upvotes: 0

Views: 2997

Answers (2)

Sergey_Klochkov
Sergey_Klochkov

Reputation: 269

I think it is much easier and less error prone to use jQuery.ajax method instead of manually creation of XMLHttpRequest object. http://api.jquery.com/jQuery.ajax/

But if you want to make your XMLHttpRequest work, you should do the following steps:

  1. Create new XMLHttpRequest object via new operator;
  2. Call method open on your XMLHttpRequest;
  3. Define onload function for callback;
  4. Call methid send of XMLHttpRequest to send request to server.

The code should be following:

var XHR = new XMLHttpRequest();
XHR.open('GET', 'some-url', true);
XHR.onload = function() {
   // here is function body
};
XHR.send();

On the server side, you should map your servlet to 'some-URL', that you'll use in your AJAX-call. You can do it in the web.xml file of your project.

Upvotes: 0

Rahul Rout
Rahul Rout

Reputation: 1323

Its true that its really easy to work with Ajax if we use Jquery but its true that we should learn about creating an XMLHttpRequest object. i am providing a working simple ajax example, i hope it helps. In the question that you asked, I could not find your servlet to be reading anything from the request object and send any response back with the result. The HTML file : (index.html)

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Servlet Test</title>
</head>
<body>
<h3>Please enter a number to Square : </h3>
<input type="text" id="numberToSquare">
<input type="button" onclick="callServlet();" value="Click To Square">
<div id="result"></div>
</body>
<script>
function callServlet()
{
    var xmlhttp;
    var input = document.getElementById('numberToSquare').value;
    if (window.XMLHttpRequest)
    {
    // This part is mainly for the latest browsers which have XMLHttpRequest object
        // like Chrome,Firefox,Safari and IE7+
    xmlhttp=new XMLHttpRequest();
    }
    else
    {
    // This should take care of the older browsers
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
xmlhttp.onreadystatechange=function()
{
/*
readyState has four different states : 
    0: request not initialized 
    1: server connection established
    2: request received 
    3: processing request 
    4: request finished and response is ready
status is ranging between 200 - Ok and 404 - Page Not Found     
*/
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
    document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ServletTest?val="+input,true);
xmlhttp.send();
}
</script>
</html>

The servlet used: (I am providing the doGet method only as the rest of the servlet is perfectly fine)

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
    // TODO Auto-generated method stub
    String val = request.getParameter("val");
    int valFromString = Integer.parseInt(val);
    Double d =  Math.pow(valFromString, 2);
    PrintWriter writer = response.getWriter();
    writer.println(d);
    System.out.println(d);
}

Upvotes: 1

Related Questions