Tutorial

jQuery AJAX JSP Servlet Java Example

Published on August 3, 2022
author

Pankaj

jQuery AJAX JSP Servlet Java Example

Ajax in Java JSP Servlet based web applications are very common. Recently I have written a lot about jQuery methods and how we can use them. Today we will look into one of the important jQuery functionality where we can easily execute AJAX calls and process the response in a Java Servlet JSP based web application.

Ajax JSP Servlet Example

I am using Eclipse IDE for creating the “Dynamic Web Project”, you can use any other IDE too. Our main focus will be towards jQuery and AJAX call from JSP to a servlet. Below image shows the final project structure. AJAX Java, Ajax JSP, Ajax Servlet, Ajax JSP Example

Ajax Servlet Code

We have a very simple servlet that gets the userName from request, create a greetings and return it as plain text.

package com.journaldev.servlets;

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;

@WebServlet("/GetUserServlet")
public class GetUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String userName = request.getParameter("userName").trim();
		if(userName == null || "".equals(userName)){
			userName = "Guest";
		}
		
		String greetings = "Hello " + userName;
		
		response.setContentType("text/plain");
		response.getWriter().write(greetings);
	}

}

Notice that I am using Servlet-3 annotations for configuration, if you like XML based configuration then you can do it in web.xml file. We will call this servlet asynchronously using jQuery AJAX support.

Ajax JSP Page

Below is our JSP page code, it has an input field where we can provide user name. As soon as focus is moved out of it, jQuery AJAX method will execute and call our servlet and process the response. index.jsp code:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jQuery, Ajax and Servlet/JSP integration example</title>

<script src="https://code.jquery.com/jquery-1.10.2.js"
	type="text/javascript"></script>
<script src="js/app-ajax.js" type="text/javascript"></script>
</head>
<body>

	<form>
		Enter Your Name: <input type="text" id="userName" />
	</form>
	<br>
	<br>

	<strong>Ajax Response</strong>:
	<div id="ajaxGetUserServletResponse"></div>
</body>
</html>

Notice that we have two JS files included in the JSP page, first one is the jQuery JS library and another one contains our JS code for ajax call. I am including jQuery JS from the code.jquery.com URL, we can also download it and keep with our JS file. JSP code is very simple, we will populate ajaxGetUserServletResponse div content from the AJAX call response through jQuery.

jQuery AJAX JavaScript File

Below is our javascript file code for jQuery AJAX request. app-ajax.js code:

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

We can also make jQuery AJAX call using it’s ajax() method, as shown below. Above is the shorthand approach to using ajax() method.

$(document).ready(function() {
	$('#userName').blur(function() {
		$.ajax({
			url : 'GetUserServlet',
			data : {
				userName : $('#userName').val()
			},
			success : function(responseText) {
				$('#ajaxGetUserServletResponse').text(responseText);
			}
		});
	});
});

Below is the syntax of the jQuery ajax() method, try to relate it to the above code and you will understand what’s going on here.

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

Our jQuery Ajax JSP Servlet Example application is ready, just build and deploy it in your favorite servlet container. Below image shows the output produced, I am using Chrome Developer tools to confirm that our servlet is getting called. jQuery AJAX Example, Ajax JSP, Ajax servlet, Ajax Java

Ajax JSP Servlet Example Summary

We learned the basics of jQuery AJAX support and how we can integrate it with Java web application, in next tutorials we will learn more features of jQuery that we can use in any web application. You can download the final project from the below link.

Download jQuery AJAX Java Web Application Project

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
November 16, 2014

Wanna become a versatile developer in JAVA domain, could you help me…?

- Antony Sebastin C

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    December 17, 2014

    How to return the same data in json format?

    - Eshan

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      January 21, 2015

      Sir , thank you very much .It works .

      - Emran Hossain

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        April 19, 2015

        Thanks! This example help me out how the ajax could be implement by javascript and jsp!

        - yuanyu

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          May 2, 2015

          Hi Pankaj, I find that this code is working perfectly in Chrome. I wrote a similar in which there is a ajax call function that connects to the server every 5 sec and fetches the date and time. it worked perfectly in chrome but not working for IE. Its only performing one call for IE and then stopping. Can you suggest a fix?

          - Gouravmoy Mohanty

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            June 10, 2015

            I don’t have a response from the Servlet. https://drive.google.com/file/d/0B1iTIMPpZHx2YlNpNFJLMUJpd28/view?usp=sharing

            - Jairo Sanchez

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              July 17, 2015

              Thank you for a tutorial! As I understand, when user make any request on server, response from servlet is automatic send back to client? Without any call from sendRedirect() or forward() or include()?

              - Radovan

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                March 22, 2016

                I want to know more…

                - sanooj

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  July 7, 2016

                  not need web.xml?

                  - huangjinku

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    July 7, 2016

                    request.getParameter(“userName”).trim()…… when request.getParameter(“userName”) is null ,there will throw an exception

                    - huangjinku

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Become a contributor for community

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      DigitalOcean Documentation

                      Full documentation for every DigitalOcean product.

                      Resources for startups and SMBs

                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                      Get our newsletter

                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                      New accounts only. By submitting your email you agree to our Privacy Policy

                      The developer cloud

                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Get started for free

                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                      *This promotional offer applies to new accounts only.