Create bar chart with JSON data using servlet and Highcharts example

In this tutorial, let us see the steps how to create bar chart with JavaScript charts (Highcharts) using JSON data generated using servlet  in eclipse. In this example, let us create a chart for gender wise pass percentage in an exam ( pass percentage of boys vs girls) since last 5 years (i.e. 2010 to 2014).

Step 1. Download Highcharts & jQuery and Place it inside js folder under WebContent. Also download java-json.jar and place it in the lib folder of the project.

Project Structure of the Project:

Highchart project structure

Step 2. Create a java bean for capturing chart data

ChartData.java


package net.javaonline.chart.form;

public class ChartData {

	int year =0;
	float boys_pass_percentage=0;
	float girls_pass_percentage=0;
	float total=0;

	public int getYear() {
		return year;
	}
	public void setYear(int year) {
		this.year = year;
	}
	public float getBoys_pass_percentage() {
		return boys_pass_percentage;
	}
	public void setBoys_pass_percentage(float boys_pass_percentage) {
		this.boys_pass_percentage = boys_pass_percentage;
	}
	public float getGirls_pass_percentage() {
		return girls_pass_percentage;
	}
	public void setGirls_pass_percentage(float girls_pass_percentage) {
		this.girls_pass_percentage = girls_pass_percentage;
	}
	public float getTotal() {
		return total;
	}
	public void setTotal(float total) {
		this.total = total;
	}

} 

Step 3. Let us create Java class for creating JSON data for the chart using the data captured in a Arraylist.

GetChartData.java

package net.javaonline.chart.dao;

import java.util.ArrayList;

import net.javaonline.chart.form.ChartData;

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

public class GetChartData {

	public String  GenerateJSonChartDataYearWisePassPercentage(String jsonp) throws  JSONException
	{

	String chartType=jsonp;

	JSONObject	finalJSonObj=new JSONObject();

	ChartData cd;

	ArrayList <ChartData> chartDataArray=new ArrayList<ChartData>(); 

	cd=new ChartData();
	cd.setYear(2010);
	cd.setBoys_pass_percentage(70);
	cd.setGirls_pass_percentage(80);
	chartDataArray.add(cd);

	cd=new ChartData();
	cd.setYear(2011);
	cd.setBoys_pass_percentage(75);
	cd.setGirls_pass_percentage(80);
	chartDataArray.add(cd);

	cd=new ChartData();
	cd.setYear(2012);
	cd.setBoys_pass_percentage(65);
	cd.setGirls_pass_percentage(90);
	chartDataArray.add(cd);

	cd=new ChartData();
	cd.setYear(2013);
	cd.setBoys_pass_percentage(90);
	cd.setGirls_pass_percentage(85);
	chartDataArray.add(cd);

	cd=new ChartData();
	cd.setYear(2014);
	cd.setBoys_pass_percentage(85);
	cd.setGirls_pass_percentage(90);
	chartDataArray.add(cd);

	JSONArray chartData=new JSONArray();
	JSONArray xaxisArr =new JSONArray();

	 JSONObject xaxisObj = new JSONObject();

	 JSONObject dataObj = new JSONObject();

	 JSONArray boys_pass_percentage =new JSONArray();
	 JSONArray girls_pass_percentage =new JSONArray();

	 for (int i=0; i<chartDataArray.size();i++)
	 {

		 System.out.println("Json data "+i);

    	 xaxisArr.put(chartDataArray.get(i).getYear());

    	 boys_pass_percentage.put(chartDataArray.get(i).getBoys_pass_percentage());
    	 girls_pass_percentage.put(chartDataArray.get(i).getGirls_pass_percentage());

	 }

 	xaxisObj.put("category", xaxisArr);

        chartData.put(xaxisObj);

     	dataObj = new JSONObject();
    	dataObj.put("name","Pass % of Boys");
     	dataObj.put("color","#FF0000");
     	dataObj.put("data",boys_pass_percentage);
     	chartData.put(dataObj);

     	dataObj = new JSONObject();
    	dataObj.put("name","Pass % of Girls");
     	dataObj.put("color","#008000");
     	dataObj.put("data",girls_pass_percentage);
     	chartData.put(dataObj);

     	System.out.println("Json data "+ chartData); 

     	finalJSonObj.put(chartType, chartData);

     	String  tempStr=jsonp+"("+finalJSonObj.toString()+")";

	    return tempStr;
}

} 

Step 4: Let us create a servlet which can be called by Ajax request.

GetChartDetails.java

package net.javaonline.chart.servlet;

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 net.javaonline.chart.dao.GetChartData;

import org.json.JSONException;
import org.json.JSONObject;

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

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

		PrintWriter out = response.getWriter();
		String jsonData="";

		try {

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

			GetChartData getChartData=new GetChartData();

			jsonData = getChartData.GenerateJSonChartDataYearWisePassPercentage(jsonp);

	       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
	}

} 

Step 5 : Let us design a html file for displaying chart. This html includes ajax call to the above servlet to retrieve JSON data and the javascript code for generating bar chart using the JSON data.   In this tutorial,  JSONP (JSON with Padding) technique is used so that we can make Ajax call  to request data from cross  domain.

HighChart.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Gender-wise Pass Percentage</title>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/highcharts.js"></script>
</head>

<body>
<div>
<table>
		<tr>
				<td align="center">
				<div id="outerDiv" style="width:100%">
				<div  id="placeholder"></div>
				</div>
				 </td>
		 </tr>
</table>
</div>

<script type="text/javascript">

$(function() {
	generateChart();

  });

function passpercentage(json) {

	$(function () {

	    var len = json.passpercentage.length
	    i = 0;

	    var options = {
	         chart: {
	                type: 'column'

	            },
	         credits: {
	     		 enabled: false
		  		},
	            title: {
	                text: 'Gender-wise Pass Percentage'
	             },
	            subtitle: {
	                text: 'Source: Test Data',
	                x: -20
	            },
	          yAxis: {
	            min: 0,
	            title: {
	                text: 'Pass Percentage'
	            }
	        },
	        plotOptions: {
	            column: {
	                pointPadding: 0.2,
	                borderWidth: 0
	            }
	        },
	        xAxis: {
	            categories: []
	        },
	        series: []
	    }

		    for (i; i < len; i++) {
		        if (i === 0) {
		            var dat = json.passpercentage[i].category,
		                lenJ = dat.length,
		                j = 0,
		                tmp;

		            for (j; j < lenJ; j++) {
		                options.xAxis.categories.push(dat[j]);
		            }
		        } else {
			        options.series.push(json.passpercentage[i]);
		        }
		    }

		$('#placeholder').highcharts(options);

	});

	}

function generateChart()
{

chartType="passpercentage";
$("#placeholder").text("");

	 $.ajax({
 			type: "GET",
			url:"http://192.168.1.7:8080/HighchartsDemo/GetChartDetails?jsonp="+chartType,
			dataType: 'jsonp',
			jsonpCallback: chartType, // the function to call
			error: function () {
				   alert("Error is occured");
					}
			}); 

}

</script>

</body>
</html>

Run the project by calling the below url

http://localhost:8080/TestWeb/HighChart.html

JSON Generated by the above application

[{“category”:[2010,2011,2012,2013,2014]},{“color”:”#FF0000″,”data”:[70,75,65,90,85],”name”:”Pass % of Boys”},{“color”:”#008000″,”data”:[80,80,90,85,90],”name”:”Pass % of Girls”}]

Generated Chart

highcharts bar chart output

 

You may download the above demo project with source code and necessary jars at  HighchartsDemo.war

You may also like

Leave a Reply

3 Comments on "Create bar chart with JSON data using servlet and Highcharts example"


Guest
maniraj
4 months 21 hours ago

when i run this code no error is shown can u please help me chart s not generated

Guest
saurabh
7 months 23 days ago

Hi,
I am getting below error
org.json.JSONException: Null key. help on it.

Guest
Ashish
8 months 3 days ago

I have run this application. I am able to get the JSON data but I am unable to get the Highchart generated. I have tried in the browser also. In the browser console, there is no error showing in it. Can you please me out whats wrong in it