Saturday 25 April 2015

Sending AJAX post request to servlet

In this post, I am going to explain, how to send a post request to a servlet and update the response in html page. I am not going to explain, each step in detail, for better understanding I refer go through the link and come back here.

Step 1: Create a dynamic webproject in eclipse and name it as “ajax_tutorial”.

Give project name as “ajax_tutorial” and press next.


Select “Generate web.xml deployment descriptor” and press Finish.

Total project structure looks like below.

Step 2: Create new jsp file “HelloWorld”.jsp like below.



HelloWorld.jsp
<!DOCTYPE html>
<html>
<head>
<script>
  function loadXMLDoc() {
    var xmlhttp;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
    } else {// code for IE6, IE5
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
      }
    }
    xmlhttp.open("POST", "/ajax_tutorial/HelloAjax", true);
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send(null);
  }
</script>
</head>
<body>

  <div id="myDiv">
    <h2>Click the button to change text</h2>
  </div>
  <button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

Step 3: Create new servlet, HelloAjax.java.
Right click on project -> New -> Servlet

Give the servlet name as “HelloAjax”.

Press Next

Press Finish


Replace following code in HelloAjax.java.
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloAjax
 */
@WebServlet("/HelloAjax")
public class HelloAjax extends HttpServlet {
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    response.getWriter().write("Hello AJAX World!");
    response.getWriter().close();
  }

}
Run “HelloWorld.jsp”, it opens in browser like below.

Click on “Change Content” button, it replace the content as “Hello AJAX World!.”.

Total project structure looks like below.




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment