Pages Navigation Menu

Coding is much easier than you think

AJAX implementation in Servlets using JQuery and JSON

 
jsonjqueryajax

In my previous post, I explained about making AJAX calls to a servlet from a JSP page and updating a part of the JSP page with a simple response from the Servlet . In this post I am going to add something more to it by making the servlet return complex Java Objects such as lists, maps, etc with the help of JSON in addition to JQuery and AJAX.
 
Here I’m going to use a JSON library in Servlet to convert this complex Java objects (lists,maps,arrays.etc) to JSON strings that will be parsed by JQuery in the JSP page and will be displayed on the web page. I am going to use google’s gson library for this purpose.
 

Library required

 
Google gson
 

Project Structure

 
Ajax using jquery and json
 

Steps done to set up our Servlet for JSON

 
From the browser perspective: jQuery
 

Jsp Page

 

<html>
<head>
<title>AJAX in Servlet using JQuery and JSON</title>
<script src="js/jquery-1.11.1.js" type="text/javascript"></script>

<script>
	$(document).ready(function() {

		$('.ajax-link').click(function() {
			$('.page-content').hide();
			var category = $(this).attr("data-category");
		       // the URL for the request
			$.get('ajaxAction', {
				// Parameter to be sent to server side
				category : category
			}, function(jsonResponse) {
				$.each(jsonResponse, function(index, value) {
					$("#" + index).html(value);
					if (index % 2 == 0) {
						$("#" + index).addClass("lightblue");
					}
				});				
				
				$('.page-content').show();	
			});
		});
	});
</script>
</head>
<body>
     <div class="main-content">
	<div>
	     <h3>Click on the links</h3>
	      <ul>
		<li><a href="#" class="ajax-link" data-category="serial">Top 5 Serial</a></li>
		<li><a href="#" class="ajax-link" data-category="movies">Top 5 Movies</a></li>
		<li><a href="#" class="ajax-link" data-category="sports">Top 5 Sports</a></li>
	      </ul>

		<h3>Result will be displayed below via Ajax</h3>
		<div class="page-content">
			<div id="0"></div>
			<div id="1"></div>
			<div id="2"></div>
			<div id="3"></div>
			<div id="4"></div>
		</div>
	</div>			
      </div>
</body>
</html>

 
jQuery allows you to fire an ajax request via get or post method and expects a JSON object as a response, as described in my previous post the first and second parameter of these method are the url and a key-value pair and the third argument of get method is a function that defines what is to be done with the response that is got back from the Servlet.
 

Code Explanation

 
In the above code jquery will fire an ajax request when user clicks on a link, for this we have binded the jQuery’s click event with each link using the class supplied on the links; Then we need to extract the category from link using jQuery’s attribute selector, and then we had binded the ajax request to ajaxAction url and passed the category as parameter and the server in turn return the required response.
 

Another must read:

 
From the server’s perspective: Servlet

In Servlet, I’m going to use a GSON library to convert Java objects (lists, maps etc) to JSON strings that will be parsed by JQuery in the JSP page and will be displayed on the web page and note that I have returned the response back to jsp based on the value of category parameter which i pass to the servlet via jQuery’s get() method.
 

Servlet

 

package com.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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

import com.google.gson.Gson;

public class JsonServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		String category = request.getParameter("category");
		List<String> result = new ArrayList<String>();

		if (category.equalsIgnoreCase("serial")) {
			result.add("Game Of Throme");
			result.add("Prison Break");
			result.add("Breaking Bad");
			result.add("Sherlok Home");
			result.add("Suits");
		} else if (category.equalsIgnoreCase("movies")) {
			result.add("Inception");
			result.add("War Horse");
			result.add("Avatar");
			result.add("Titanic");
			result.add("Life is Beautiful");
		} else if (category.equalsIgnoreCase("sports")) {
			result.add("Basket Ball");
			result.add("Football");
			result.add("Tennis");
			result.add("Rugby");
			result.add("Cricket");
		}

		String json = new Gson().toJson(result);
		response.setContentType("application/json");
		response.getWriter().write(json);
	}
}

 

Web.xml

Servlet mapping should be done in web.xml as shown below
 

<web-app ..>
<servlet>
  <servlet-name>AjaxAction</servlet-name>
  <servlet-class>com.action.JsonServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>AjaxAction</servlet-name>
  <url-pattern>/ajaxAction</url-pattern>
</servlet-mapping>
<welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

 

Demo

 
On clicking ‘Top 5 Serial’ the following response appears
 
Json serial
 
On clicking ‘Top 5 Movies’ the following response appears
 
Json movie
 
download
 

Other Ajax tutorial from our Blog

 

Reference

  • jQuery.get()
  • jQuery.each()
  • Wikipedia : JSON
  •  

    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.

    • Saul

      Hi, it’s help me. thank’s a lot

    • Akhil Sudhakaran

      Thanks dear. It really works…But I want to do without gson library. want to pass list directly to ajax

    • Pranoti

      Hey i want to retrive values from database table to a dropdown list ,suggest me how do i write a code in java and jsp file.

    • Bhavesh

      really awesome. thank you so much. it’s perfectly work.

    • Jaya

      This code made my day.. thanks a lot..

    • Jk

      Can you please give me some suggestions for paopulating the combo box values

    • http://gravatar.com/mohan8797 mohan8797ohan

      how to make it in struts1.x getting values from db

    • Asif

      Not working

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

        Hello Asif,

        I Personally feel there is no error… the same code is working for me..please recheck the java script syntax that your getting in response

    • http://gravatar.com/somyaranjan somyaranjan

      not working for me!!
      my dropdowns are not getting populated….

      • Jk

        Yes Drop down not getting paopulated

    • Nikhil Dethe

      great example…thankx alot…

    • zubair

      i want to populate drop down with the field of database

      • Meghna

        hey i want to implement same thing with one more addition is that suppose this page has next and we land on another screen(jsp) now when we do previous from that screen i want see the dropdown should be populated with same assciated players list (sports name can fetched from DB which we might insert on click of next) while displaying the name of the player in the dropdown to the user which i had selected last time.

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

          Hi store those values in session , before navigating to next page… and use them back