DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Creating a Polar Chart to Measure Electromagnetic Field Strength
  • Top 4 Gantt Chart Solutions for React
  • Understanding Google Analytics 4, Server-Side Tracking, and GDPR Compliance
  • Validate XML Request Against XML Schema in Mule 4

Trending

  • Automated Testing Lifecycle
  • TDD With FastAPI Is Easy
  • LTS JDK 21 Features
  • Selecting the Right Automated Tests
  1. DZone
  2. Coding
  3. Languages
  4. Drawing Google Chart From Servlet JSON Response

Drawing Google Chart From Servlet JSON Response

Sandeep Patel user avatar by
Sandeep Patel
·
Jun. 10, 13 · Interview
Like (0)
Save
Tweet
Share
25.86K Views

Join the DZone community and get the full member experience.

Join For Free

  • 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
JSON Chart Google (verb)

Published at DZone with permission of Sandeep Patel, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Creating a Polar Chart to Measure Electromagnetic Field Strength
  • Top 4 Gantt Chart Solutions for React
  • Understanding Google Analytics 4, Server-Side Tracking, and GDPR Compliance
  • Validate XML Request Against XML Schema in Mule 4

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: