Pages Navigation Menu

Coding is much easier than you think

AJAX in Servlet & jsp using JQuery – Java web application

 
jQuery-Ajax-Servlet-Jsp
 
Implementing Ajax features in a Java web application will be so easy if you are using JQuery library; Since this library provides built-in methods that can be used to enable Ajax. In this post, I am going to demonstrate the JQuery’s Ajax capability using on blur event in java web application.
 

Folder Structure

 
jquery-ajax-basic
 
As highlighted in the image download the jQuery library and place in js folder of eclipse work-space, and refer this jQuery files in the head section in the jsp, this jQuery file is responsible for the AJAX call made to the servlet and for updating the response back in the JSP.
 

Jsp Page

 

<html>
<head>
<title>AJAX in java web application using jQuery</title>
<script src="js/jquery-1.11.1.js" type="text/javascript"></script>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>
<form>
  <fieldset>
    <legend>AJAX implementation in JSP and Servlet using JQuery</legend>
    <br /> Enter your Name: <input type="text" id="userName" />
 </fieldset>

 <fieldset>
   <legend>Response from jQuery Ajax Request on Blur event</legend>
   <div id="ajaxResponse"></div>
 </fieldset>
</form>
</body>
</html>

 

JS File

 
File: ajax.js
In this file we will fire ajax via jquery get method to call java servlet

$(document).ready(function() {
	$('#userName').blur(function(event) {
		var name = $('#userName').val();
		$.get('JqueryServlet', {
			userName : name
		}, function(responseText) {
			$('#ajaxResponse').text(responseText);
		});
	});
});

 
Here when the user types a name in the “userName textbox” and click anywhere outside the textbox, then its blur event gets triggered and the ‘get’ function executes the Ajax GET request on the Servlet. Here the first argument of get method is the URL, second argument is a key-value pair that passes the parameter from JSP to Servlet and the third argument is a function that defines what is to be done with the response that is got back from the Servlet.
 
Note :
This get method is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

 

Recommended reading:

  • Ajax implementation without jQuery library
  • jQuery Tutorial for Beginners
  •  

    Servlet

     
    Now let’s go on and write the servlet which handles this Ajax call

    package com.servlet;
    
    import java.io.IOException;
    import javax.servlet.ServletException;
    
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class JqueryServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    protected void doGet(HttpServletRequest request,
    	HttpServletResponse response) throws ServletException, IOException {
    
    	String userName = request.getParameter("userName");
    	if (userName.equals("")) {
    		userName = "User name cannot be empty";
    	} else {
    		userName = "Hello " + userName;
    	}
    	response.setContentType("text/plain");
    	response.getWriter().write(userName);
    }
    }
    

    I hope the code above is self explanatory.
     

    Another must read:

     

    Web.xml

     
    Make sure you have done servlet mapping in web.xml as shown below

    <web-app>
      <display-name>JqueryAjaxServlet</display-name>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      <servlet>
        <servlet-name>JqueryServlet</servlet-name>
        <servlet-class>com.servlet.JqueryServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>JqueryServlet</servlet-name>
        <url-pattern>/JqueryServlet/*</url-pattern>
      </servlet-mapping>
    </web-app>
    

     

    Demo

     
    AJAX-implementation-in-JSP-and-Servlet-using-JQuery
     
    On running the application the above webpage is generated, in which enter a value in the textbox and click anywhere outside the textbox, then you will see a welcome message saying “Hello (userName)”.

    Note: In our next article I have explained on how to return complex Java objects such as list, map, etc. as response to a ajax call.
     
    download
     

    Reference

     

    About Mohaideen Jamil


    Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

    • http://www.simplecodestuffs.com/ Mohaideen Jamil

      No, you can use post as well .. there are lot of Ajax methods which we have to use based on our code and requirement..

      Please refer http://www.w3schools.com/jquery/jquery_ref_ajax.asp for more

    • Phil

      Hi Mohaideen,

      This is a great example and has helped to understand the concept / relationship between Servlet and Ajax.

      Thanks again.

      • http://www.simplecodestuffs.com Mohaideen Jamil

        Thanks for your feedback :)

    • baram204

      Thanks, Mohaideen. I understand how things working between JSP(or HTML) and Servlet with AJAX!!

      • http://www.simplecodestuffs.com Mohaideen Jamil

        Most welcome :)