Tuesday, September 30, 2014

Calling a Servlet Using JQuery Ajax

When developing web applications it is very common to use Ajax to call a Servlet and get a desired response.
In this lesson I will show you how to use JQuery to send an Ajax call to a Servlet.

1. First create a new web applications(In eclipse : New => Dynamic Web Project)
2. Right click on the src folder and create a new Servlet(New => Servlet). I name the servlet as MyServlet.
3. Change the servlet so that it prints some meaningful text. My servlet is as below.

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
       
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter pw = response.getWriter();
pw.println("Hello from server via GET...!");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter pw = response.getWriter();
pw.println("Hello from server via POST...!");
}
}

4. Right. Servlet is created. Now I need to call this servlet from JQuery.
5. Create a new JSP page in web apps folder. I name it as index.jsp.
6. Now change the contents of the page as below.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
   $('#btn').click(function() {
    $.ajax({
           type:"POST",
           url:"MyServlet"
       })
       .done(function (data) {
    alert(data);//data object represents the response
       });
   });
});
</script>
</head>
<body>
<input type="button" value="Call Servlet" id="btn"/>
</body>
</html>

7. That is all. Now run the application in tomcat server and click the "Call Servlet" button and you will get an alert saying "Hello from server via POST...!". The POST method has been called.
Now change the parameter 'type:"POST"' to 'type:"GET"'. Now your message will be "Hello from server via GET...!". It means the GET method has been called.

Note - 1 :- By default this ajax call is asynchronous. It means after the ajax call is executed the rest of the code continues executing without waiting for the response from the servlet. If you want to get rid of this asynchronous behavior, just add the parameter  'async:false' as below.

$.ajax({
type:"POST",
url:"MyServlet",
async:false
})

Note - 2 :- JQuery has below two shorthands to call GET and POST requests. If you want you can use them instead of above $.ajax function.

$.get('MyServlet', function(data) {
//alert(data);
});

$.post('MyServlet', function(data) {
//alert(data);
});

8 comments:

  1. It has been simply incredibly generous with you to provide openly what exactly many individuals would’ve marketed for an eBook to end up making some cash for their end, primarily given that you could have tried it in the event you wanted.
    Click here:
    <a=title="Angularjs training in chennai"
    href="https://www.besanttechnologies.com/training-courses/web-designing-training/angularjs-training-in-chennai</a>

    ReplyDelete

  2. Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.
    python training chennai|python training institute in chennai

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete