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.