FusionCharts offers a set of JavaScript charts that use simple XML and JSON formats to feed data to the graphs. FusionCharts provides a large variety of different types of charts that you can use in your demos. JSP is one of the most widely used technologies that help software developers create dynamically generated web pages. While we already have detailed documentation on how JSP can be easily integrated with FusionCharts using the FusionCharts-JSP wrapper, this article talks about how you can use the MongoDB database along with FusionCharts and JSP for rendering charts. MongoDB, one of the most popular document-oriented databases, that also stores data records as documents, which helps in handling big data and provides high scalability and performance. In this article, we’ll explore how to integrate JSP with MongoDB and create a chart using FusionCharts. We choose MongoDB over others because it is an open-source and document-oriented. It works on the concept of document and collections, stored data in the JSON format and can also vary in structure as per the requirement.

Now, as we have covered the basics sufficiently, let’s get started with the steps to create charts using JSP and MongoDB…

To get the code (for creating charts) in this blog working, we need to first install the following components: Make sure that all the above mentioned components have been downloaded in your system. To setup MongoDB on your operating system, please refer to the documentation here. Next, we move on to how you can configure MongoDB and create a database Only three steps and we will be done with the database part! To know how you can set up MongoDb on your OS, refer to the documentation here. Step 1: Create a json file that contains the data that goes into the database and will be used as the source data for the chart. We’ll name this file as country.json.
[{
	"label": "China",
	"value": 8800.0
}, {
	"label": "India",
	"value": 5800.0
}, {
	"label": "United States",
	"value": 4200.0
}, {
	"label": "Indonesia",
	"value": 6200.0
}, {
	"label": "Australia",
	"value": 7900
}, {
	"label": "Brazil",
	"value": 4400.0
}]
Step 2: Import the .json file created in Step 1 into mongodb using the “mongoimport” command as shown below. import Step 3: Next, open another shell to run the “mongo” command. mongo Step 4: Now we need to verify if our data has been imported correctly into the database or no. To do this, you need to execute the following commands:
  • Use the “show dbs” command to see your database. A list of the databases present is shown.
  • From this list, select the required database using the “use ” command.
  • Next, use the “show collections” command to see the collections inside your database.
  • For seeing the contents of a specific collection, execute the “db..find().pretty()” command.
population You can import this demo database from here. With this, we are done with creating the database. Now we move on to creating chart objects and then finally rendering the chart. Step 1: Create a JSP page and import all the packages in a script tag. The code below imports the com.google.gson package that enables the conversion from JSON to Java and Java to JSON. Before getting into the code, let’s first talk about the google-gson library. The google-gson library:
  • Provides the toJson() and fromJson() methods for converting Java objects to JSON and the other way round
  • Allows conversion of the already existing unmodifiable objects to and from JSON
  • Supports Java Generics extensively
  • Allows custom representations of objects
  • Supports arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)
Now, here is the code to import the com.google.gson package:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="com.mongodb.*" %>
<%@page import="java.util.*" %>
<%@page import="com.google.gson.*" %>
<%@page import="fusioncharts.FusionCharts" %>
Click here for more information on google-gson package. Step 2: Establish database connectivity to fetch values from the database and place them inside a hashmap, as shown in the code snippet below.
<%

//Make sure you have included MongoDB jar files in order to use the MongoDB java driver classes

         Mongo mongoClient = new Mongo("localhost" , 27017 );
			
         //connecting to the database
         DB db = mongoClient.getDB( "fusioncharts" );
         System.out.println("Connected to database successfully");
         
         //Hashmap is created to store the values from the database
         HashMap<String,Integer> labelValue = new HashMap<String,Integer>();
         
         //fetching the collection from the database
        DBCollection collection = db.getCollection("simpledata");
        
        //Selects the documents in a collection and returns a cursor to the selected        documents
         DBCursor cursor = collection.find();
         
         while(cursor.hasNext()) {
           
             DBObject o = cursor.next();
             
                String label = (String) o.get("label") ; 
                int value = ((Number) o.get("value")).intValue();
              labelValue.put(label, value);
            
                }
  %>
Once the database connectivity is established, structure your data in the Fusioncharts format and convert the java objects to their JSON representation using the GSON library. Step 3: Finally, create a constructor and pass the necessary parameters to render the chart.
<%
    
            Gson gson = new Gson();
            
            // The 'chartobj' map object holds the chart attributes and data.
            chartobj.put("caption", "Split of Visitors by Age Group");
            chartobj.put("subCaption" , "Last year");
            chartobj.put("paletteColors" , "#0075c2");
            chartobj.put("bgColor" , "#ffffff");
            chartobj.put("showBorder" , "0");
            chartobj.put("theme","fint");
            chartobj.put("showPercentValues" , "1");
            chartobj.put("decimals" , "1");
            chartobj.put("captionFontSize" , "14");
            chartobj.put("subcaptionFontSize" , "14");
            chartobj.put("subcaptionFontBold" , "0");
            chartobj.put("toolTipColor" , "#ffffff");
            chartobj.put( "toolTipBorderThickness" , "0");
            chartobj.put("toolTipBgColor" , "#000000");
            chartobj.put("toolTipBgAlpha" , "80");
            chartobj.put("toolTipBorderRadius" , "2");
            chartobj.put("toolTipPadding" , "5");
            chartobj.put("showHoverEffect" , "1");
 
          // to store the entire data object
            ArrayList arrData = new ArrayList();
            for(Map.Entry m:labelValue.entrySet()) 
            {
                // to store the key value pairs of label and value object of the data object
                Map<String, String> lv = new HashMap<String, String>();
                lv.put("label", m.getKey().toString() );
                lv.put("value", m.getValue().toString());
                arrData.add(lv);             
            }
            //close the connection.
            cursor.close();
 
            //create 'dataMap' map object to make a complete FC datasource.
             Map<String, String> dataMap = new LinkedHashMap<String, String>();  
        /*
            gson.toJson() the data to retrieve the string containing the
            JSON representation of the data in the array.
        */
         dataMap.put("chart", gson.toJson(chartobj));
         dataMap.put("data", gson.toJson(arrData));

            FusionCharts columnChart= new FusionCharts(
            "column2d",// chartType
                        "chart1",// chartId
                        "600","400",// chartWidth, chartHeight
                        "chart",// chartContainer
                        "json",// dataFormat
                        gson.toJson(dataMap) //dataSource
                    );
            %>
                            
            <%=columnChart.render()%>
Given below is the full JSP code of the example we worked on:
<%-- 
    Document   : singleseries-mongodb-example
    Author     : fusioncharts
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="com.mongodb.*" %>
<%@page import="java.util.*" %>
<%@page import="com.google.gson.*" %>
<%@page import="fusioncharts.FusionCharts" %>

<%

         Mongo mongoClient = new Mongo("localhost" , 27017 );
			
         //connecting to the database
         DB db = mongoClient.getDB( "fusioncharts" );
         System.out.println("Connected to database successfully");
         
         //Hashmap is created to store the values from the database
         HashMap<String,Integer> labelValue = new HashMap<String,Integer>();
         
         //fetching the collection from the database
        DBCollection collection = db.getCollection("simpledata");
        
        //Selects the documents in a collection and returns a cursor to the selected documents
         DBCursor cursor = collection.find();

         while(cursor.hasNext()) {
           
             DBObject o = cursor.next();
             
                String label = (String) o.get("label") ; 
                int value = ((Number) o.get("value")).intValue();
              labelValue.put(label, value);
            
                }
  %>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Creating Charts with Data from a Database - fusioncharts.com</title>

 
        <script src="fusioncharts.js"></script>
        <script src="fusioncharts.theme.fint.js"></script>
        <script src="fusioncharts.charts.js"></script>

    </head>
    <body>
         <div id="chart"></div>

        <%
         
            Gson gson = new Gson();
            
            // The 'chartobj' map object holds the chart attributes and data.
            chartobj.put("caption", "Split of Visitors by Age Group");
            chartobj.put("subCaption" , "Last year");
            chartobj.put("paletteColors" , "#0075c2");
            chartobj.put("bgColor" , "#ffffff");
            chartobj.put("showBorder" , "0");
            chartobj.put("theme","fint");
            chartobj.put("showPercentValues" , "1");
            chartobj.put("decimals" , "1");
            chartobj.put("captionFontSize" , "14");
            chartobj.put("subcaptionFontSize" , "14");
            chartobj.put("subcaptionFontBold" , "0");
            chartobj.put("toolTipColor" , "#ffffff");
            chartobj.put( "toolTipBorderThickness" , "0");
            chartobj.put("toolTipBgColor" , "#000000");
            chartobj.put("toolTipBgAlpha" , "80");
            chartobj.put("toolTipBorderRadius" , "2");
            chartobj.put("toolTipPadding" , "5");
            chartobj.put("showHoverEffect" , "1");
         
           // to store the entire data object
            ArrayList arrData = new ArrayList();
            for(Map.Entry m:labelValue.entrySet()) 
            {
                // to store the key value pairs of label and value object of the data object
                Map<String, String> lv = new HashMap<String, String>();
                lv.put("label", m.getKey().toString() );
                lv.put("value", m.getValue().toString());
                arrData.add(lv);             
            }
            //close the connection.
            cursor.close();
 
            //create 'dataMap' map object to make a complete FC datasource.
             Map<String, String> dataMap = new LinkedHashMap<String, String>();  
        /*
            gson.toJson() the data to retrieve the string containing the
            JSON representation of the data in the array.
        */
         dataMap.put("chart", gson.toJson(chartobj));
         dataMap.put("data", gson.toJson(arrData));

            FusionCharts columnChart= new FusionCharts(
            "column2d",// chartType
                        "chart1",// chartId
                        "600","400",// chartWidth, chartHeight
                        "chart",// chartContainer
                        "json",// dataFormat
                        gson.toJson(dataMap) //dataSource
                    );
            %>
            
<!--    Step 5: Render the chart    -->                
            <%=columnChart.render()%>
        
    </body>
</html>
Finally, simply run your JSP file using MongoDB. You output looks like as shown below: sc1 If you see any errors in your code, click here to download the complete source code of the sample project we have created for this tutorial.

Was There a Problem Rendering Charts?

In case something went wrong and you are unable to see the chart, check for the following:
  • The chart ID should be unique for each chart rendered on the same page. Otherwise, it will result in a JavaScript error.
  • If the chart does not show up at all, check if the fusioncharts.js and fusioncharts wrapper FusionCharts.java was loaded. Also, check if the path to fusioncharts.js and FusionCharts.java file is correct, and whether the file exists in that location.

Take your data visualization to a whole new level

From column to donut and radar to gantt, FusionCharts provides with over 100+ interactive charts & 2,000+ data-driven maps to make your dashboards and reports more insightful

Explore FusionCharts

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.