Highcharts is one of the popular javascript library used to produce user-friendly charts for a given set of data. We can generate different types of graphical representations of the data with the help of the Highcharts library.

In this article, we will learn how to integrate the Highcharts javascript library into spring boot web application. We will create a spring boot web application, which will read the JSON data through AJAX call and display the bar chart on the HTML page.

Let us begin! 🙂

Create a Spring boot application with required dependencies

Create a new Spring boot application with required dependencies. For this example, we need to add spring-boot-starter-web and spring-boot-starter-thymeleaf dependencies.

The pom.xml file with the required dependencies is given below.

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.3.BUILD-SNAPSHOT</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.asb.example</groupId>
	<artifactId>spring-boot-highcharts-example</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-boot-highcharts-example</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
		<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

Configure the web application

To redirect the Spring web application to a default landing page make the following changes to the Spring boot application class.

In the below code, we are implementing the WebMvcConfigurer interface and overriding the addViewControllers method to set the default landing view to landig-page.

package com.asb.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootApplication
public class SpringBootHighchartsExampleApplication implements WebMvcConfigurer {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootHighchartsExampleApplication.class, args);
	}

	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/").setViewName("landing-page");
	}
}

Create the REST endpoint

We need to create a RESTful endpoint to return the required data. For this, create a REST controller called HighChartController.java as shown below.

package com.asb.example.controller;

import java.util.Map;
import java.util.TreeMap;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HighChartController {

	@GetMapping("/get-data")
	public ResponseEntity<Map<String, Integer>> getPieChart() {
		Map<String, Integer> graphData = new TreeMap<>();
		graphData.put("2016", 147);
		graphData.put("2017", 1256);
		graphData.put("2018", 3856);
		graphData.put("2019", 19807);
		return new ResponseEntity<>(graphData, HttpStatus.OK);
	}
}

Here, we are returning a map containing blog statistics. The map keys are having calendar years and map values are having page view count. The RESTful endpoint is exposed on the path /get-data.

In this example, we are using static data by returning hard coded values. We can also return the data from a database by using spring data jpa and other ways(retrieving from other services, etc).

Create the HTML page

We have mapped the landing page by setting the view name to landing-page in the previous step. Create a HTML page called landing-page.html under /src/main/resources/templates/ directory. Add the following content.

<!DOCTYPE html>
<html xmlns="https://www.thymeleafe.org">
<head>
<meta charset="ISO-8859-1">
<title>High Chart Example - Spring Boot</title>
<link rel="stylesheet"
	href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet"
	href="https://code.highcharts.com/css/highcharts.css" />
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script
	src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
</head>
<body>
	<div align="center">
		<h2>Spring Boot Highcharts Example</h2>
	</div>
	<figure class="highcharts-figure">
		<div id="container-bar"></div>
	</figure>
	<script type="text/javascript">
		$(document).ready(
				function() {
					$.ajax({
						url : "/get-data",
						success : function(result) {
							var yearDtls = [];
							var countDtls = [];
							console.log(result);
							Object.keys(result).forEach(
									function(key) {
										yearDtls.push(key);
										countDtls.push(result[key]);
									});
							drawChart(yearDtls, countDtls);
						}
					});
				});

		function drawChart(year, viewCounts) {
			Highcharts.chart('container-bar', {
				chart : {
					type : 'column',
					styledMode : true
				},
				title : {
					text : 'Blog Page view count'
				},
				xAxis : [ {
					title : {
						text : 'Year'
					},
					categories : year
				} ],
				yAxis : [ {
					className : 'highcharts-color-0',
					title : {
						text : 'Page View Count'
					}
				} ],
				series : [ {
					data : viewCounts
				} ]
			});
		}
	</script>
</body>
</html>

Here, we are adding the required javascript libraries and CSS files. We have added Bootstrap and Highchart CSS and js files. We have also added the JQuery javascript library to the header part of the HTML page.

We are loading the JSON data from the backend to show the bar graph through JQuery AJAX call to the /get-data endpoint.

Once the data is loaded, we are plotting the chart by using Highcahrts.chart() method of the Highcharts library.

This method takes the HTML element id and chart configuration as the method parameter. We have passed container-bar as the HTML element id(Id of the <div> element used to plot the Highchart)

Few of the Highchart configurations used in this example are given below. We are plotting the blog statistics using a bar chart.

  • chart: Setting related to the chart.
  • title: To set the Highchart title.
  • xAxis: To set up the configuration related to the X-axis of the graph.
  • yAxis: To set up the configuration related to the Y-axis of the graph.
  • series: The list of values to be used to plot the chart.

Running the application

Start the spring boot application. We should be able to get the bar chart as shown below.

Highchart example with spring boot

Conclusion

In this article, we learned how to integrate the Highcharts javascript library into Spring boot web application. We have learned how to load the data into an HTML page using AJAX call and display the graphical representation of the data.

Sample code is available on GitHub. Happy coding! 🙂

Please subscribe to get the latest updates into your mailbox. 🙂

Processing…
Success! You're on the list.

You may also interested in