HighChart using AJAX, JSP and Servlet

We know that HighChart 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 http://www.highcharts.com/ for more information.

You can integrate HighChart with any server side technology but here I will show you how to integrate HighChart using AJAX, JSP and Servlet. This tutorial shows step by step so that we can understand how it happens. It displays the data for site visitors log in line chart. I have also put a calendar for date-picker so that you can pick a custom range of dates and get the visitor statistics in HighChart. The calendar has more features like you can select Today, Yesterday, Last One week, Last One month etc. On mouse hover on the line chart you can see the visitors count on a particular date.


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

Prerequisites

JDK 1.7
Eclipse 3.6
Maven 2.x
Tomcat Server 7.x
HighChart API

Final Output

HighChart using AJAX, JSP and Servlet

Now we will see steps how to implement it

Step 1. Create a maven based web project in Eclipse

Step 2. Modify pom.xml file as shown below

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.roytuts</groupId>
    <artifactId>roy-app</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>roy-app Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>2.2.4</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>roy-app</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Step 3. Modify web.xml file as shown below

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
      <servlet-name>HighChartServlet</servlet-name>
      <display-name>HighChartServlet</display-name>
      <description></description>
      <servlet-class>com.roytuts.servlets.HighChartServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>HighChartServlet</servlet-name>
      <url-pattern>/HighChartServlet</url-pattern>
  </servlet-mapping>
 
  <welcome-file-list>
        <welcome-file>chart.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Step 4. Create a POJO class for HighChart data model

package com.roytuts.pojo;

public class ChartModel {

  private String date;
  private String minTemp;
  private String maxTemp;

  public ChartModel(String date, String minTemp, String maxTemp) {
    this.date = date;
    this.minTemp = minTemp;
    this.maxTemp = maxTemp;
  }

  public String getDate() {
    return date;
  }

  public void setDate(String date) {
    this.date = date;
  }

  public String getMinTemp() {
    return minTemp;
  }

  public void setMinTemp(String minTemp) {
    this.minTemp = minTemp;
  }

  public String getMaxTemp() {
    return maxTemp;
  }

  public void setMaxTemp(String maxTemp) {
    this.maxTemp = maxTemp;
  }

}

Step 5. Create sample static data for HighChart. You will usually fetch dynamic data from your database and show your data onto HighChart.

package com.roytuts.repository;

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

import com.roytuts.pojo.ChartModel;

public class ChartData {

  private static final List<ChartModel> CHART_MODELS;

  static {
    CHART_MODELS = new ArrayList<ChartModel>();
    CHART_MODELS.add(new ChartModel("06/01/2015", "28", "35"));
    CHART_MODELS.add(new ChartModel("06/02/2015", "25", "39"));
    CHART_MODELS.add(new ChartModel("06/03/2015", "26", "40"));
    CHART_MODELS.add(new ChartModel("06/04/2015", "22", "33"));
    CHART_MODELS.add(new ChartModel("06/05/2015", "21", "34"));
    CHART_MODELS.add(new ChartModel("06/06/2015", "25.6", "38.6"));
    CHART_MODELS.add(new ChartModel("06/07/2015", "20.9", "38.4"));
    CHART_MODELS.add(new ChartModel("06/08/2015", "27.8", "39.1"));
    CHART_MODELS.add(new ChartModel("06/09/2015", "25", "37"));
    CHART_MODELS.add(new ChartModel("06/10/2015", "38.1", "40.2"));
    CHART_MODELS.add(new ChartModel("06/11/2015", "30.5", "41"));
    CHART_MODELS.add(new ChartModel("06/12/2015", "27", "38.9"));
    CHART_MODELS.add(new ChartModel("06/13/2015", "26.4", "39.7"));
    CHART_MODELS.add(new ChartModel("06/14/2015", "26.3", "39.7"));
    CHART_MODELS.add(new ChartModel("06/15/2015", "23.4", "38.4"));
    CHART_MODELS.add(new ChartModel("06/16/2015", "22", "39"));
    CHART_MODELS.add(new ChartModel("06/17/2015", "24", "38"));
    CHART_MODELS.add(new ChartModel("06/18/2015", "26", "40.5"));
    CHART_MODELS.add(new ChartModel("06/19/2015", "26", "39.4"));
    CHART_MODELS.add(new ChartModel("06/20/2015", "23", "39"));
    CHART_MODELS.add(new ChartModel("06/21/2015", "25.4", "38"));
    CHART_MODELS.add(new ChartModel("06/22/2015", "26.1", "39"));
  }

  public static List<ChartModel> getHighChartDataList() {
    return CHART_MODELS;
  }

}

Step 6. Create a servlet that will handle request and response from a user

package com.roytuts.servlets;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.roytuts.pojo.ChartModel;
import com.roytuts.repository.ChartData;

/**
 * Servlet implementation class HighChartServlet
 */
public class HighChartServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  List<ChartModel> chartModels;

  /**
   * @see HttpServlet#HttpServlet()
   */
  public HighChartServlet() {
    chartModels = ChartData.getHighChartDataList();
  }

  /**
   * @see Servlet#init(ServletConfig)
   */
  @Override
  public void init(ServletConfig config) throws ServletException {}

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request, response);
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String json = "";
    String sDate = request.getParameter("start");
    String eDate = request.getParameter("end");
    if (sDate != null && eDate != null) {
      System.out.println("Start Date : " + sDate);
      System.out.println("End Date : " + eDate);
      //Actual data should come from database
      //select data from database based on start date and end date
      //here I am neither going to fetch data from database nor fetch data based on date range
      //you need to manipulate those things from database
      int counter = 1;
      if (chartModels != null) {
        json += "[";
      }
      for (ChartModel chartModel : chartModels) {
        try {
          json += "[" + (new SimpleDateFormat("MM/dd/yyyy")).parse(chartModel.getDate()).getTime() + "," + chartModel.getMinTemp() + ","
              + chartModel.getMaxTemp() + "]";
          if (counter < chartModels.size()) {
            json += ",";
          }
          counter++;
        } catch (ParseException e) {
          e.printStackTrace();
        }
      }
      if (chartModels != null) {
        json += "]";
      }
      if (chartModels == null) {
        json = "No record found";
      }
    } else {
      json = "Date must be selected.";
    }
    System.out.println(json);
    response.getWriter().write(json);
  }

}

Step 7. Create a JSP file for viewing the graph

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Highchart using JSP, Servlet</title>
<link rel="stylesheet"
    href="<%=request.getContextPath()%>/assets/css/bootstrap.min.css">
<link rel="stylesheet"
    href="<%=request.getContextPath()%>/assets/css/daterangepicker.css">
<script type='text/javascript'
    src="<%=request.getContextPath()%>/assets/js/jquery-1.9.1.min.js"></script>
<script type='text/javascript'
    src="<%=request.getContextPath()%>/assets/js/jquery-migrate-1.2.1.js"></script>
<script type='text/javascript'
    src="<%=request.getContextPath()%>/assets/js/jquery-ui-1.10.3-custom.min.js"></script>
<script type='text/javascript'
    src='<%=request.getContextPath()%>/assets/js/sugar.min.js'></script>
<script type='text/javascript'
    src='<%=request.getContextPath()%>/assets/js/exporting.js'></script>
<script type='text/javascript'
    src='<%=request.getContextPath()%>/assets/js/highcharts.js'></script>
<script type='text/javascript'
    src='<%=request.getContextPath()%>/assets/js/highcharts-more.js'></script>
<script type='text/javascript'
    src='<%=request.getContextPath()%>/assets/js/script.js'></script>
<script type='text/javascript'
    src='<%=request.getContextPath()%>/assets/js/daterangepicker.js'></script>
</head>
<body>
    <div style="margin: 10px 0 0 10px;">
        <h3>Highchart Example using AJAX, JSP and Servlet</h3>
        <form class="form-horizontal">
            <fieldset>
                <div class="input-prepend">
                    <span class="add-on"><i class="icon-calendar"></i> </span> <input
                        type="text" name="range" id="range" />
                </div>
            </fieldset>
        </form>
        <div id="msg"></div>
        <div id="chart"></div>
    </div>
</body>
</html>

Step 8. AJAX call through jQuery and HighChart API

$(function() {

    // Set the default dates
    var startDate = Date.create().addDays(-6), // 7 days ago
    endDate = Date.create(); // today

    var range = $('#range');

    // Show the dates in the range input
    range.val(startDate.format('{MM}/{dd}/{yyyy}') + ' - '
            + endDate.format('{MM}/{dd}/{yyyy}'));

    // Load chart
    ajaxLoadChart(startDate, endDate);

    range.daterangepicker({
        startDate : startDate,
        endDate : endDate,
        ranges : {
            'Today' : [ 'today', 'today' ],
            'Yesterday' : [ 'yesterday', 'yesterday' ],
            'Last 7 Days' : [ Date.create().addDays(-6), 'today' ],
            'Last 30 Days' : [ Date.create().addDays(-29), 'today' ]
        }
    }, function(start, end) {
        ajaxLoadChart(start, end);
    });

    // Function for loading data via AJAX and showing it on the chart
    function ajaxLoadChart(startDate, endDate) {
        // If no data is passed (the chart was cleared)
        if (!startDate || !endDate) {
            return;
        }
        // Otherwise, issue an AJAX request
        $.post('http://localhost:8080/roy-app/HighChartServlet', {
            start : startDate.format('{MM}/{dd}/{yyyy}'),
            end : endDate.format('{MM}/{dd}/{yyyy}')
        }, function(data) {
            if ((data.indexOf("No record found") > -1)
                    || (data.indexOf("Date must be selected.") > -1)) {
                $('#msg').html('<span style="color:red;">' + data + '</span>');
            } else {
                $('#msg').empty();
                $('#chart').highcharts({
                    chart : {
                        type : 'arearange',
                        zoomType : 'x'
                    },

                    title : {
                        text : 'Temperature variation by day'
                    },

                    xAxis : {
                        type : 'datetime'
                    },

                    yAxis : {
                        title : {
                            text : null
                        }
                    },

                    tooltip : {
                        crosshairs : true,
                        shared : true,
                        valueSuffix : '°C'
                    },

                    legend : {
                        enabled : false
                    },

                    series : [ {
                        name : 'Temperatures',
                        data : data
                    } ]
                });
            }
        }, 'json');
    }
});

Step 9. Download below assets directory and put it under webapp directory

assets

Step 10. Run the application on Tomcat server. You will get the desired output in the browser.

That’s all. Thanks for reading.

Soumitra Roy Sarkar

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

0 Replies to “HighChart using AJAX, JSP and Servlet”

  1. Hi, My name is Ashish Sarkar. I have tried this Highchart using my own logic. So I have taken the servlets and jsp and I am converting the data into Json data. The problem I am facing is the Null Pointer Exception. I read some oracle docs for the cause of Null Pointer Exception. I realized there is some misconception implementation in “contextpath”. I tried to change the context path. But I still get the same error.
    SEVERE: Servlet.service() for servlet [jsp] in context with path [/MavenPractice] threw exception [java.lang.NullPointerException] with root cause java.lang.NullPointerException

    I dont have the option to show you my code. If you can provide me your mail address, I can mail you my project. please help me out.

    Thanks
    Ashish Sarkar

Leave a Reply

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