Google Chart using Struts 2

Introduction

In this tutorial I will build Google chart using Struts 2; actually, it is a pie chart using Google chart API. The backend will be built on Struts 2 framework. The JSP page will be used for displaying data on Google pie chart.
You might 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.

You can integrate Google chart with any server-side technology but here I will show you how to integrate Google chart using Struts 2. The pie chart displays data for area-wise top seven countries in in the world. 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 persistence sources. You can change the source of data as per your requirements.

struts 2 google pie chart

Prerequisites

Java 1.6+, Maven 3.8.2, Gradle 4.x, Struts 2.3.16 – 2.5.26, jsp-api 2.1 – 2.3.3, Servlet 3.1.0 – 4.0.1

Project Setup

You can create a gradle or maven based project in your favorite IDE or tool. The name of the project is struts2-google-pie-chart.

If you are using Gradle as a build tool, then you can sue the following build.gradle. Make sure to adjust according to the your gradle version.

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')
}

If you are using maven as a build tool then you can use the following pom.xml file:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.roytuts</groupId>
	<artifactId>struts2-google-pie-chart</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>8</maven.compiler.source>
		<maven.compiler.target>8</maven.compiler.target>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>2.5.26</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.1</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.3</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>

	<build>
		<finalName>struts2-google-pie-chart</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
			</plugin>
		</plugins>
	</build>
</project>

Deployment Descriptor

The deployment descriptor file is required as this is an web application using Struts 2 framework. The following configuration for the web.xml file is used. The web.xml file is kept under the src/main/webapp/WEB-INF folder.

<?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"> -->
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xmlns="https://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee
                        https://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    id="WebApp_ID"
    version="4.0">

	<display-name>Google Pie Chart using Struts 2</display-name>

	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
		<!--<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>

In the above descriptor file notice that I have commented out the version 3.0 because I used to test with Servlet version 4.x. So, this example code has been tested with both Servlet 3.x and 4.x. Therefore, if you are using Servlet version 3.x then you can use the web descriptor version 3.0 or if you are using Servlet version 4.x then you can use the descriptor version 4.0.

Notice another thing, I have commented out fully packaged StrutsPrepareAndExecuteFilter. So, it depends on your Struts 2 version. Adjust this filter class according to your Struts 2 version. If you are using Struts 2 version 2.5 or greater then you need to use the first one otherwise you need to use the second one. Another option to verify the full package of the filter class is to find this filter class in your class path library. In Eclipse IDE you can easily search by pressing CTRL+Shift+t keys.

Struts 2 Action Class

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

public class PieChartAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	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;
	}

}

Sample Pie Chart Data

Then I 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.

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;
		}
	}

}

View File

Create a view called src/main/webapp/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.roytuts.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>

If everything is done please deploy and run the application and verify the output on browser. Hit the URL http://localhost:8085/ struts2-google-pie-chart/struts.jsp or http://localhost:8085/struts2-google-pie-chart/ to display data on the pie chart.

Finally, you have successfully built an example on Google chart using struts 2.

Testing Pie Chart Application

Run the build command to generate the WAR file from the project and deploy the war file under Tomcat server.

Once you hit the URL http://localhost:8085/struts2-google-pie-chart/ then you will get the following result on the brwoser. Note that my Tomcat server is running on port 8085.

google pie chart using struts 2

Source Code

Download

1 thought on “Google Chart using Struts 2

  1. No result defined for action com.action.SebaHome and result [‘Russia’,17098242],[‘Canada’,9984670],[‘USA’,9826675],[‘China’,9596961],[‘Brazil’,8514877],[‘Australia’,7741220],[‘India’,3287263]

Leave a Reply

Your email address will not be published.