May 14, 2011

Ajax GET request example - Barebones (with Java on the server side)

1) Create a JSP, GetExample.jsp and add it to the WebContent folder of the web application


<html>
<head>
<title>Barebones Ajax - Get Example</title>


<script type="text/javascript">


var request = null;


function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
    request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
    try {
      request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (failed) {
  request = null;
         }
    }
}
if (request == null) {  alert("Error creating request object");   }
}


function doHello() {
createRequest();
request.open("GET", "hello?name="+document.forms[0].elements[0].value, true);
request.onreadystatechange = updatePage;
request.send(null);

}


var updatePage = function() {
if (request.readyState == 4) {
if (request.status == 200) {
        var responseStr = request.responseText;
    document.getElementById('message').innerHTML = responseStr;
}
}
}
</script>


</head>
<body>


<h1>Kindly type your name</h1>


<form>
<label>Name</label>: <input type="text" name="name" /><br/><br/>
<input type="button" value="Submit" onclick="javascript:doHello();"/> 
</form>
<br/>
<div id="message"></div>


</body>
</html>


2) Create a servlet, HelloServlet.java and add it to the src folder of the web application


import java.io.*;
import javax.servlet.http.*;


public class HelloServlet extends HttpServlet {

public void doGet (HttpServletRequest req, HttpServletResponse res) throws IOException {

String name = req.getParameter("name");
PrintWriter out = res.getWriter();
out.print("<h2>Hello " + name + "</h2>");
}
}


3) Configure the servlet in the web.xml file,


<servlet>
   <servlet-name>hello</servlet-name>
   <servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>hello</servlet-name>
   <url-pattern>/hello</url-pattern>
</servlet-mapping>


4) Test the example by typing the following URL in the browser,

http://localhost:8080/WebAppName/hello

No comments:

Post a Comment