JSONP example to read data from cross domain using Ajax & Servlet

In this tutorial, let us see how to read JSON data from different (cross) domain using AJAX call to servlet. In my earlier JSON tutorial, JSON data was generated in the servlet and the same was read by AJAX / JQuery from the same domain and displayed in a Browser. As we know, Ajax request (XmlHttpRequest) does not allow cross domain data exchange(see Same Origin Policy ), then how to read JSON data from different domain with Ajax request. Solution is to do a simple trick using JSON with Padding (i.e. JSONP). JSONP enables Ajax to request data from cross domain.

3 things to do

1. Calling servlet or JSON file with callback function name parameter

2. Appending (prefix) callback function name with final json data (JSONP) in servlet.

2. Create a call back function in javascript for parsing and displaying json result data.

In this example, let us read Student Mark details as JSON object from cross domain using AJAX. The complete code is given below.

Servlet & DAO class:

Servlet (GetStudentMarkDetails.java)

package javaonline;

import java.io.IOException;
import java.io.PrintWriter;
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.JSONException;

/**
 * Servlet implementation class GetDetails
 */
@WebServlet("/javaonline/GetStudentMarkDetails")
public class GetStudentMarkDetails extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetStudentMarkDetails() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("application/json;charset=UTF-8"); 

		response.setHeader("Cache-Control", "no-cache"); 

		//get the PrintWriter object to write the html page
		PrintWriter out = response.getWriter();

	String jsonpDataStr="";

		try {

			String callbackFunc=request.getParameter("jsonp");

			GetDetailsDAO getDetailsDAO=new GetDetailsDAO();

			jsonpDataStr = getDetailsDAO.getJSONPStudentData(callbackFunc);
		  	System.out.println("Final Json " + jsonpDataStr);

	       out.print(jsonpDataStr);

	    } catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
	        out.close();
	    }

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

DAO class to generate JSON data (getJSONPStudentData.java)

	public String getJSONPStudentData(String callbackFunc) throws  JSONException
	{
		String jsonpDataStr="";

			JSONObject jSonDataArrObj;
			JSONObject jSonDataFinalArrObj;

			JSONObject studentMarkDetails;
			JSONArray studentMarkDetailsArr;

			JSONArray jSonDataFinalArr;
			jSonDataFinalArr =new JSONArray(); 

	  	 studentMarkDetails = new JSONObject();
		 studentMarkDetails.put("rollNo", "5000");
		 studentMarkDetails.put("Name", "Jacob");
		 studentMarkDetails.put("M1", "90");
		 studentMarkDetails.put("M2", "93");
		 studentMarkDetails.put("M3", "92");

  	         studentMarkDetailsArr =new JSONArray();
		 studentMarkDetailsArr.put(studentMarkDetails);

		 jSonDataArrObj=new JSONObject();
		 jSonDataArrObj.put("JsonData", studentMarkDetailsArr);

		 jSonDataFinalArr.put(jSonDataArrObj);

		 studentMarkDetails = new JSONObject();
		 studentMarkDetails.put("rollNo", "5001");
		 studentMarkDetails.put("Name", "Kamal");
		 studentMarkDetails.put("M1", "65");
		 studentMarkDetails.put("M2", "92");
		 studentMarkDetails.put("M3", "67");

		 studentMarkDetailsArr =new JSONArray();
		 studentMarkDetailsArr.put(studentMarkDetails);

		 jSonDataArrObj=new JSONObject();
		 jSonDataArrObj.put("JsonData", studentMarkDetailsArr);

		 jSonDataFinalArr.put(jSonDataArrObj);

		 jSonDataFinalArrObj=new JSONObject();

		 jSonDataFinalArrObj.put("JSonDataFinal", jSonDataFinalArr);

		 jsonpDataStr=jSonDataFinalArrObj.toString();

		    return callbackFunc +"("+jsonpDataStr+")"; //padding callbackfunction

		}
	}

HTML file (JSonPRead.html):

<!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>JSon Data Parsing</title>
  <style type="text/css">

</style>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
</head>
<body>

<div id="fullDiv" style="width:100%" >

<input name="test" type="button" value="Get Output" onClick="GetOutput();">

<div id="output"></div>

</div>											

<script type="text/javascript">

//<strong>Call back function</strong>
function GetStudentJson(json) {

	  var table="<html><table border=\"1px\">";

	  table=table+"<th> Roll No.</th><th>Name</th><th>Mark1</th><th>Mark2</th><th>Mark3</th>";

		var finalJsonData=json.JSonDataFinal;

		  $.each(finalJsonData, function(index, element) {
			  var jsonData = element.JsonData;

			  table=table+"<tr>";

			  $.each(jsonData, function(index, element) {
					  table=table+"<td>" + element.rollNo +"</td><td>"
					  + element.Name +"</td><td>" + element.M1 +"</td><td>" + element.M2 +"</td><td>" +element.M3 +"</td>";
				    });
				  table=table+"</tr>";

		  });
		  table=table+="</table></html>";

		  $("#output").html(table);

	}

	function GetOutput()
	{

	 $.ajax({

			type: "GET",
							//calling cross domain servelt using jquery ajax
	 	        url: "http://localhost:8080/TestWeb/javaonline/GetStudentMarkDetails?jsonp=GetStudentJson",
		 	dataType: 'jsonp',
			jsonpCallback: 'GetStudentJson', // the jsonpCallback function to call
			async: false,
			global: false,
			error: function () {
				   alert("Errr is occured");
							}
						});
 	   }

</script>

</body>
</html>

Calling  the JSonPRead.html page

http://localhost:8080/TestWeb/javaonline/JSonPRead.html

Output :

JSON Read Cross Domain

 

Generated JSON data in server side:

GetStudentJson({“JSonDataFinal”:[{“JsonData”:[{“M1″:”90″,”M2″:”93″,”M3″:”92″,”rollNo”:”5000″,”Name”:”Jacob”}]},{“JsonData”:[{“M1″:”65″,”M2″:”92″,”M3″:”67″,”rollNo”:”5001″,”Name”:”Kamal”}]}]})

where GetStudentJson is the call back function

You may also like

Leave a Reply

1 Comment on "JSONP example to read data from cross domain using Ajax & Servlet"


Guest
kundan
1 month 7 hours ago

good example