We know that Google chart basically displays different statistical data on different chart types such as column chart, bar chart, line chart, pie chart etc. You can have a look at the URL https://developers.google.com/chart/ for more information before reading this tutorial on Google chart using Struts 2.

You can integrate Google chart with any server side technology but here I will show you how to integrate Google chart using Struts 2. This tutorial shows step by step so that we can understand how it happens. It displays the data for area-wise top seven countries in pie chart. You can also use other charts for other purposes. In this example I have used static sample data and the actual data should come from database or other sources. You can change the source of data as per your requirements.

If you have any query please feel free to leave a comment.

Prerequisites

JDK 1.6
Knowledge of Struts 2, Java
Apache Tomcat v7
Eclipse IDE
Jars

Google chart using Struts2
Final Output

When chart renders on the view

Google Chart API

When mouse hover happens on chart

Google Chart API

Now we will see how it happens step by step.

Step 1. Create the Dynamic Web Project in Eclipse IDE. The required project structure gets created in the IDE.

Step 2. Put all jar files under WEB-INF/lib directory.

If you do not want to create Dynamic Web Project and instead want to create Grdale based project then build using below build.gradle script which will save you from downloading individual jar libraries from different sites.

plugins {
    id 'war'  
}

apply plugin: 'java'

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    mavenLocal()
    mavenCentral()
}
    
dependencies {
    compile('org.apache.struts:struts2-core:2.3.16.1')
    providedCompile('javax.servlet.jsp:jsp-api:2.1')
    providedCompile('javax.servlet:javax.servlet-api:3.1.0')
}

Here is the image of Gradle based project structure. You may need to go to the options given below for making such structure from the Eclipse.

Do right click on the project -> click Properties -> click Project facets -> check the box Dynamic Web Module (make sure version at least 3.0).

google chart using struts 2

Step 3. Now modify deployment descriptor – web.xml. Paste the below code in your web.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>Google Chart using Struts 2</display-name>
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<welcome-file-list>
		<welcome-file>struts.jsp</welcome-file>
	</welcome-file-list>
</web-app>

Step 4. Create Struts Action Class that extends ActionSupport class to get benefits of default implementations provided in the ActionSupport class.

package com.jeejava.google.chart.struts.actions;

import java.util.List;

import com.jeejava.google.chart.data.PieChartData;
import com.jeejava.google.chart.data.PieChartData.KeyValue;
import com.opensymphony.xwork2.ActionSupport;

public class PieChartAction extends ActionSupport {
	private static final long serialVersionUID = 7038588781945164147L;
	private String pieChartData;
	private List<KeyValue> pieDataList;

	public PieChartAction() {
		this.pieDataList = PieChartData.getPieDataList();
	}

	public String getPieChartData() {
		if (pieChartData == null || pieChartData.trim().length() <= 0) {
			populateData();
		}
		return pieChartData;
	}

	private void populateData() {
		StringBuilder stringBuilder = new StringBuilder();
		for (KeyValue pieData : pieDataList) {
			stringBuilder.append("[");
			stringBuilder.append("'");
			stringBuilder.append(pieData.getKey());
			stringBuilder.append("'");
			stringBuilder.append(",");
			stringBuilder.append(pieData.getValue());
			stringBuilder.append("]");
			stringBuilder.append(",");
		}
		pieChartData = stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1);
	}

	@Override
	public String execute() throws Exception {
		return SUCCESS;
	}
}

Step 5. Then we will create sample data for showing on Google Pie Chart. So create a class PieChartData.java as shown below. This file contains area-wise top seven countries in the world. These dummy data are required in order to complete the example on google chart using struts 2.

package com.jeejava.google.chart.data;

import java.util.ArrayList;
import java.util.List;

public class PieChartData {
	private static final List<KeyValue> pieDataList;
	static {
		pieDataList = new ArrayList<PieChartData.KeyValue>();
		pieDataList.add(new KeyValue("Russia", "17098242"));
		pieDataList.add(new KeyValue("Canada", "9984670"));
		pieDataList.add(new KeyValue("USA", "9826675"));
		pieDataList.add(new KeyValue("China", "9596961"));
		pieDataList.add(new KeyValue("Brazil", "8514877"));
		pieDataList.add(new KeyValue("Australia", "7741220"));
		pieDataList.add(new KeyValue("India", "3287263"));
	}

	public static List<KeyValue> getPieDataList() {
		return pieDataList;
	}

	public static class KeyValue {
		String key;
		String value;

		public KeyValue(String key, String value) {
			super();
			this.key = key;
			this.value = value;
		}

		public String getKey() {
			return key;
		}

		public void setKey(String key) {
			this.key = key;
		}

		public String getValue() {
			return value;
		}

		public void setValue(String value) {
			this.value = value;
		}
	}

}

 

Step 6. Create a view called struts.jsp which will render the Google Pie Chart along with the data from Struts Action class. Notice in the below jsp view file how we have used Google API to initialize chart with Java’s bean class.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Google Chart - Struts 2</title>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
    // Load the Visualization API and the piechart package.
    google.load('visualization', '1.0', {
        'packages' : [ 'corechart' ]
    });
    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);
    // Callback that creates and populates a data table,
    // instantiates the pie chart, passes in the data and
    // draws it.
    function drawChart() {
        // Create the data table.    
        var data = google.visualization.arrayToDataTable([
                [ 'Country', 'Area(square km)' ],
                <s:bean name="com.jeejava.google.chart.struts.actions.PieChartAction" var="pieData" />
                <s:property value="#pieData.pieChartData" />
                ]);
        // Set chart options
        var options = {
            'title' : 'Area-wise Top Seven Countries in the World',
            is3D : true,
            pieSliceText : 'label',
            tooltip : {
                showColorCode : true
            },
            'width' : 900,
            'height' : 500
        };
        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.PieChart(document
                .getElementById('chart_div'));
        chart.draw(data, options);
    }
</script>
</head>
<body>
	<div style="width: 600px;">
		<div id="chart_div"></div>
	</div>
</body>
</html>

Step 7. If everything is done please deploy and run the application and verify the output on browser. Hit the URL http://<host>:<port>/<context-path>/struts.action. For example  http://localhost:8080/google-chart/struts.action or http://localhost:8080/google-chart-struts2/

Congratulations! You have successfully finished example on Google chart using struts 2.

Thanks for your reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *