JSON in Servlet with Ajax call

JSON in Servlet with Ajax call

JSON in Servlet with Ajax call:


JSON is a amazing alternate for XML to pass/transfer the informations. It is required to know how to handle JSON in servlet.

In servlet it can be handled like this,

// json is the JSON object.

But if you want to call your servlet through ajax, then we should handle the JSON response in JS also to display JSON in jsp page, else only object object will be printed in JSP page.

Ajax JS changes to display JSON:

// for json [if responseText is JSON ]

// for string [if responseText is String ]

Now I am going to create a dynamic web project to display returned JSON object in JSP.

Folder Structure:
JSON Ajax servlet folder structure


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSON with Ajax call in Servlet Example | Javadomain.in </title>
<script src="js/jquery-1.11.2.min.js" type="text/javascript"></script>
<script src="js/javadomain.js" type="text/javascript"></script>
<div id="printJSON"></div>


$(document).ready(function() {
		name = "ngdeveloper.com";
		// on page load itself calling servlet and printing the JSON value in JSP page
                $.get('JSONAjaxServlet', {
                        siteName : name
                }, function(responseText) {

                	// for json [if responseText is JSON ]

                    // for string [if responseText is String ]
                      //  $('#printJSON').text(responseText);



package in.javadomain;

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

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

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

 * Servlet implementation class JSONAjaxServlet
public class JSONAjaxServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 try {
             JSONObject json =  WriteJson();
             PrintWriter out = response.getWriter();
         } catch (IOException e) {

	// sample method with JSON return
	private JSONObject WriteJson() {
		JSONObject obj = new JSONObject();
		obj.put("SiteName", "ngdeveloper.com");
		obj.put("URL", "http://www.ngdeveloper.com");
		obj.put("Content", "Programming Tutorials");
		return obj;


Ajax JSON in JSP page

1,310 total views, 1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.