Provides Tutorials on Web Technologies.

Drawing Google Chart From Servlet JSON Response


  • Google provides Visualization API to draw charts and other components.
  • More Details can be found on :-
          https://developers.google.com/chart/interactive/docs/
  • Different type of ready to use chart types are exposed a java script classes to the developers for customize.
  • In this Demo, "We will see how a visualization charts get rendered in browser for a JSON data response from a Servlet".
  • Project Structure,
  • The java servlet uses GSON API jar library for converting a array list of student data to its JSON representation.
          StudentJsonDataServlet.java code below,


package com.sandeep.visual.servlet;

import java.io.IOException;
import java.util.ArrayList;
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 com.google.gson.Gson;
import com.sandeep.visual.data.Student;

@WebServlet("/StudentJsonDataServlet")
public class StudentJsonDataServlet extends HttpServlet {

 private static final long serialVersionUID = 1L;

 public StudentJsonDataServlet() {
  super();
 }

 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

  List<Student> listOfStudent = getStudentData();

  Gson gson = new Gson();

  String jsonString = gson.toJson(listOfStudent);

  response.setContentType("application/json");

  response.getWriter().write(jsonString);

 }

 private List<Student> getStudentData() {

  List<Student> listOfStudent = new ArrayList<Student>();
  Student s1 = new Student();
  s1.setName("Sandeep");
  s1.setComputerMark(75);
  s1.setMathematicsMark(26);
  listOfStudent.add(s1);

  Student s2 = new Student();
  s2.setName("Bapi");
  s2.setComputerMark(60);
  s2.setMathematicsMark(63);
  listOfStudent.add(s2);

  Student s3 = new Student();
  s3.setName("Raja");
  s3.setComputerMark(40);
  s3.setMathematicsMark(45);
  listOfStudent.add(s3);

  Student s4 = new Student();
  s4.setName("Sonu");
  s4.setMathematicsMark(29);
  s4.setComputerMark(78);
  listOfStudent.add(s4);

  return listOfStudent;
 }
}

  • The JSON response data format is as below,

  •  The HTML markup is present in visualization-chart-demo.html file,
<html>
 <head>
  <title>Google Visualization Chart Demo</title>
 </head>
 
 <body>
  <div id="student-bar-chart"></div>
  
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <script type="text/javascript" src="https://www.google.com/jsapi"></script>
  <script type="text/javascript" src="./js/visualization-chart-script.js"></script>
 </body>
</html>
  • The above html has a "DIV#student-bar-chart" html element for bar chart container.It calls JQUERY and JSAPI library from Google hosted CDN.Finally it calls our script code present in
    visualization-chart-script.js file.
var TUTORIAL_SAVVY = {

 /*return google visualization data*/
 getvisualizationData: function (jsonData) {

  var point1, point2, dataArray = [],

   data = new google.visualization.DataTable();

  data.addColumn('string', 'Name');

  data.addColumn('number', 'Marks in Mathematics');

  data.addColumn({
    type: 'string',
    role: 'tooltip',
    'p': {
     'html': true
    }
   });

  data.addColumn('number', 'Marks In Computer');

  data.addColumn({
    type: 'string',
    role: 'tooltip',
    'p': {
     'html': true
    }
   });

  /* for loop code for changing inputdata to 'data' of type google.visualization.DataTable*/
  $.each(jsonData, function (i, obj) {

   point1 = "Math : " + obj.mathematicsMark + "";

   point2 = "Computer : " + obj.computerMark + "";

   dataArray.push([obj.name, obj.mathematicsMark, TUTORIAL_SAVVY.returnTooltip(point1, point2), obj.computerMark, TUTORIAL_SAVVY.returnTooltip(point1, point2)]);
  });

  data.addRows(dataArray);

  return data;
 },
 /*return options for bar chart: these options are for various configuration of chart*/
 getOptionForBarchart: function () {

  var options = {
   animation: {
    duration: 2000,
    easing: 'out'
   },

   hAxis: {
    baselineColor: '#ccc'
   },
   vAxis: {
    baselineColor: '#ccc',
    gridlineColor: '#fff'
   },

   isStacked: true,
   height: 400,
   backgroundColor: '#fff',
   colors: ["#68130E", "#c65533"],
   fontName: 'roboto',
   fontSize: 12,
   legend: {
    position: 'top',
    alignment: 'end',
    textStyle: {
     color: '#b3b8bc',
     fontName: 'roboto',
     fontSize: 12
    }
   },
   tooltip: {
    isHtml: true,
    showColorCode: true,
    isStacked: true
   }
  };
  return options;
 },
 /*Draws a Bar chart*/
 drawBarChart: function (inputdata) {

  var barOptions = TUTORIAL_SAVVY.getOptionForBarchart(),

   data = TUTORIAL_SAVVY.getvisualizationData(inputdata),

   chart = new google.visualization.ColumnChart(document.getElementById('student-bar-chart'));

  chart.draw(data, barOptions);
  /*for redrawing the bar chart on window resize*/
  $(window).resize(function () {

   chart.draw(data, barOptions);
  });
 },
 /* Returns a custom HTML tooltip for Visualization chart*/
 returnTooltip: function (dataPoint1, dataPoint2) {

  return "<div style='height:30px;width:150px;font:12px,roboto;padding:15px 5px 5px 5px;border-radius:3px;'>" +
   "<span style='color:#68130E;font:12px,roboto;padding-right:20px;'>" + dataPoint1 + "</span>" +
   "<span style='color:#c65533;font:12px,roboto;'>" + dataPoint2 + "</span></div>";
 },
 /*Makes ajax call to servlet and download data */
 getStudentData: function () {

  $.ajax({

    url: "StudentJsonDataServlet",

    dataType: "JSON",

    success: function (data) {

     TUTORIAL_SAVVY.drawBarChart(data);
    }
   });
 }
};

google.load("visualization", "1", {
  packages: ["corechart"]
 });

$(document).ready(function () {

 TUTORIAL_SAVVY.getStudentData();
});
  • The above javascript has following function with its purpose:-
           getStudentData() ----- On DOM ready it makes an AJAX call and download the Student data.
           drawBarChart()------ On SUCCESS of AJAX call this method get called.
           getOptionForBarchart()-----Return the CONFIGURATION for bar chart.
           getvisualizationData()------Formats the JSON data to Google Visualization Data format.
           returnTooltip()-------Returns the HTML string for CUSTOM tooltip.
  • The output bar chart :-

  • Download Link for the Demo project:-
           project download link