Write JSON in servlet & read using jQuery and JavaScript

In many situations, you may require to generate JSON data in server side so that it can be read and parsed in Client side using jQuery and Javascript just like reading XML data using Ajax / jQuery and Javascript.
In my earlier tutorial, JSON was created and read in Java. Here, let us create JSON data using java (i.e. in server side) and read using jQuery  & Javascript in client side. In this example, Employee details such as Employee code, name, designation and pay are captured as JSON object and JSON Array is created for each employee. A servlet & DAO class is used to generate JSon data. In HTML, the JSON data is read, parsed and displayed in table format using jQuery & Javascript.
Note: Database connection may be used for creating dynamic JSON data with multiple employee details.

Servlet & DAO class:

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/GetDetails")
public class GetDetails extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetDetails() {
        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 jsonData="";

		try {

		  GetDetailsDAO getDetailsDAO=new GetDetailsDAO();

		   jsonData = getDetailsDAO.getJsonData();

	       out.print(jsonData);

	    } 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
//DB connection may be used for generating dynamic json data


package javaonline;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class GetDetailsDAO {

	public String getJsonData() throws  JSONException
	{
		String jsonData="";

			JSONObject empDetails;
			JSONObject jSonDataObj;
			JSONObject jSonDataFinalObj;

			JSONArray empDetailsArr;
			JSONArray jSonDataFinalArr;
			jSonDataFinalArr =new JSONArray(); 

	  	 empDetails = new JSONObject();
		 empDetails.put("Code", "1234");
		 empDetails.put("Name", "Kumar");
		 empDetails.put("Desig", "SO");
		 empDetails.put("Pay", "Rs.22221/-");

  	         empDetailsArr =new JSONArray();
		 empDetailsArr.put(empDetails);

		 jSonDataObj=new JSONObject();
		 jSonDataObj.put("JsonData", empDetailsArr);

		 jSonDataFinalArr.put(jSonDataObj);

		 empDetails = new JSONObject();
		 empDetails.put("Code", "1235");
		 empDetails.put("Name", "Wilson");
		 empDetails.put("Desig", "AO");
		 empDetails.put("Pay", "Rs.62222/-");

		 empDetailsArr =new JSONArray();
		 empDetailsArr.put(empDetails);

		 jSonDataObj=new JSONObject();
		 jSonDataObj.put("JsonData", empDetailsArr);

		 jSonDataFinalArr.put(jSonDataObj);

		 jSonDataFinalObj=new JSONObject();

		 jSonDataFinalObj.put("JSonDataFinal", jSonDataFinalArr);

		 jsonData=jSonDataFinalObj.toString();

	  	System.out.println("Final Json " + jsonData);

		    return jsonData;

		}

	} 

HTML file (JsonRead.html) for reading , parsing and displaying in table format using jQuery and JavaScript


<!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="getJsonData();">

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

</div>											

<script type="text/javascript">

	function getJsonData()
	{

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

	  table=table+"<th> Code</th><th>Name</th><th>Desig.</th><th>Pay</th>";

	  $.ajax({

			type: "GET",
						url: "/TestWeb/javaonline/GetDetails",
						dataType: 'json',
						success : function(json) {

							var info1=json.JSonDataFinal;

						  $.each(info1, function(index, element) {
							  var info = element.JsonData;

							  table=table+"<tr>";

								  $.each(info, function(index, element) {

									  table=table+"<td>" + element.Code +"</td><td>"
									  + element.Name +"</td><td>" + element.Desig +"</td><td>" + element.Pay +"</td>";
								    });
								  table=table+"</tr>";

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

						  $("#output").html(table);
						},
						async: false,
						global: false,
						error: function () {
						   alert("Errr is occured");
						}
					});
}

</script>

</body>
</html> 

Run the program by calling the html file (JSaonRead.html) and click on GetOutput.

json read jquery

Generated JSON data in server side:

{“JSonDataFinal”:[{“JsonData”:[{“Pay”:”Rs.22221/-“,”Code”:”1234″,”Desig”:”SO”,”Name”:”Kumar”}]},{“JsonData”:[{“Pay”:”Rs.62222/-“,”Code”:”1235″,”Desig”:”AO”,”Name”:”Wilson”}]}]}

You may also like

Leave a Reply

Be the First to Comment!