杰瑞科技汇

FusionCharts Java如何集成与使用?

Of course! Here is a comprehensive guide on how to use FusionCharts with Java, covering the most common integration methods.

FusionCharts Java如何集成与使用?-图1
(图片来源网络,侵删)

Overview: FusionCharts and Java

FusionCharts is a JavaScript charting library that renders interactive charts and dashboards in the browser. Java, on the other hand, is a server-side language. Therefore, Java does not render the charts directly. Instead, your Java application's role is to:

  1. Prepare Data: Fetch data from a database, an API, or any other source.
  2. Format Data: Convert this data into the JSON format that FusionCharts requires.
  3. Pass Data to the Frontend: Embed this JSON data into an HTML page, which is then served to the user's browser.
  4. Render the Chart: The browser executes the FusionCharts JavaScript, which reads the JSON and draws the chart.

Let's explore the two primary ways to achieve this.


Method 1: The Classic Approach (JSP/Servlet)

This is a traditional and straightforward method, perfect for simple applications or those built on the JSP/Servlet framework.

Step-by-Step Guide

Step 1: Add FusionCharts Library

FusionCharts Java如何集成与使用?-图2
(图片来源网络,侵删)

First, you need to include the FusionCharts JavaScript library in your project. The easiest way is to use a CDN.

In your JSP file (index.jsp), add the following script tag in the <head> section.

<!-- index.jsp -->
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">FusionCharts with Java</title>
    <!-- 1. Include FusionCharts library -->
    <script src="https://cdn.fusioncharts.com/fusioncharts/latest/fusioncharts.js"></script>
    <script src="https://cdn.fusioncharts.com/fusioncharts/latest/themes/fusioncharts.theme.fusion.js"></script>
</head>
<body>
    <h1>My First Chart with Java</h1>
    <div id="chart-container">Chart will render here</div>
    <!-- 2. Java code to generate JSON data -->
    <%
        // a. Prepare your data (e.g., from a database)
        String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun"};
        int[] values = {12, 19, 3, 5, 2, 3};
        // b. Build the JSON data string
        // This is a simple example. For real apps, use a JSON library like Gson or Jackson.
        String jsonData = "{ \"chart\": { \"caption\": \"Monthly Sales Data\", \"xaxisname\": \"Month\", \"yaxisname\": \"Sales\", \"theme\": \"fusion\" }, \"data\": [";
        for (int i = 0; i < labels.length; i++) {
            jsonData += "{\"label\": \"" + labels[i] + "\", \"value\": \"" + values[i] + "\"}";
            if (i < labels.length - 1) {
                jsonData += ",";
            }
        }
        jsonData += "]}";
        // c. Pass the JSON data to a JavaScript variable
    %>
    <script>
        var chartData = <%= jsonData %>;
        // 3. Initialize and render the chart
        FusionCharts.ready(function() {
            var salesChart = new FusionCharts({
                type: 'column2d', // Chart type
                renderAt: 'chart-container', // Container ID
                width: '700',
                height: '400',
                dataFormat: 'json',
                dataSource: chartData
            });
            salesChart.render();
        });
    </script>
</body>
</html>

Explanation:

  1. Include Library: We include fusioncharts.js and a theme (fusioncharts.theme.fusion.js) from the CDN.
  2. Java (JSP) Logic: The Java code inside <% ... %> block runs on the server.
    • It creates sample arrays for labels and values.
    • It manually constructs a JSON string. Note: For production, use a proper JSON library (like Gson or Jackson) to avoid errors and security vulnerabilities.
    • It assigns the JSON string to a JavaScript variable chartData using <%= ... %>. This prints the value of the variable directly into the HTML.
  3. JavaScript Logic:
    • FusionCharts.ready() ensures the library is loaded before rendering.
    • A new FusionCharts object is created with configuration options (type, renderAt, etc.).
    • dataSource: chartData tells FusionCharts to use the JSON data we generated from Java.
    • salesChart.render() draws the chart inside the div with id="chart-container".

Method 2: The Modern Approach (Spring Boot with Thymeleaf)

This is a more robust and scalable approach for modern web applications. We'll use the Spring Boot framework, which simplifies backend development, and Thymeleaf for templating.

FusionCharts Java如何集成与使用?-图3
(图片来源网络,侵删)

Step-by-Step Guide

Step 1: Set up a Spring Boot Project

Use the Spring Initializr to create a new project with the following dependencies:

  • Spring Web
  • Thymeleaf

Step 2: Add FusionCharts Library

In src/main/resources/templates/index.html, add the FusionCharts CDN links in the <head> section.

<!-- src/main/resources/templates/index.html -->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">FusionCharts with Spring Boot</title>
    <script src="https://cdn.fusioncharts.com/fusioncharts/latest/fusioncharts.js"></script>
    <script src="https://cdn.fusioncharts.com/fusioncharts/latest/themes/fusioncharts.theme.fusion.js"></script>
</head>
<body>
    <h1>My Chart with Spring Boot</h1>
    <div id="chart-container">Chart will render here</div>
    <!-- Thymeleaf will insert the JSON data here -->
    <script th:inline="javascript">
        /*<![CDATA[*/
        var chartData = /*[[${chartData}]]*/ {};
        FusionCharts.ready(function() {
            var salesChart = new FusionCharts({
                type: 'column2d',
                renderAt: 'chart-container',
                width: '700',
                height: '400',
                dataFormat: 'json',
                dataSource: chartData
            });
            salesChart.render();
        });
        /*]]>*/
    </script>
</body>
</html>

Explanation:

  • xmlns:th="http://www.thymeleaf.org" declares the Thymeleaf namespace.
  • <script th:inline="javascript"> enables Thymeleaf's JavaScript inlining.
  • /*[[${chartData}]]*/ {} is the key part. It tells Thymeleaf to evaluate the expression ${chartData} (a variable from the backend) and print its value directly into the JavaScript code. The is a fallback in case the variable is null.

Step 3: Create the Controller

Create a Java controller class to handle the request and prepare the data.

// src/main/java/com/example/demo/ChartController.java
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ChartController {
    @GetMapping("/")
    public String showChart(Model model) {
        // 1. Prepare your data (e.g., from a database)
        String[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun"};
        int[] values = {12, 19, 3, 5, 2, 3};
        // 2. Build the JSON data string
        StringBuilder jsonDataBuilder = new StringBuilder();
        jsonDataBuilder.append("{ \"chart\": { \"caption\": \"Monthly Sales Data\", \"xaxisname\": \"Month\", \"yaxisname\": \"Sales\", \"theme\": \"fusion\" }, \"data\": [");
        for (int i = 0; i < labels.length; i++) {
            jsonDataBuilder.append("{\"label\": \"").append(labels[i]).append("\", \"value\": \"").append(values[i]).append("\"}");
            if (i < labels.length - 1) {
                jsonDataBuilder.append(",");
            }
        }
        jsonDataBuilder.append("]}");
        // 3. Add the data to the model to be passed to the view
        model.addAttribute("chartData", jsonDataBuilder.toString());
        // 4. Return the name of the HTML template to render
        return "index";
    }
}

Explanation:

  • @Controller marks this class as a Spring MVC controller.
  • @GetMapping("/") maps this method to the root URL ().
  • The Model object is used to pass data from the controller to the view (the HTML template).
  • We build the JSON string (again, for production, use Gson/Jackson).
  • model.addAttribute("chartData", ...) makes the JSON data available under the key chartData in the template.
  • return "index"; tells Spring to render the index.html template.

Step 4: Run the Application

Run your SpringBootApplication.java class. Navigate to http://localhost:8080 in your browser. You will see the chart rendered.


Best Practice: Using a JSON Library (Gson)

Manually building JSON strings is error-prone. It's highly recommended to use a library like Google Gson.

How to Use Gson

  1. Add Gson Dependency:

    • Maven (pom.xml):
      <dependency>
          <groupId>com.google.code.gson</groupId>
          <artifactId>gson</artifactId>
          <version>2.10.1</version>
      </dependency>
    • Gradle (build.gradle):
      implementation 'com.google.code.gson:gson:2.10.1'
  2. Refactor Your Java Code:

    Instead of building a string, create POJOs (Plain Old Java Objects) and let Gson serialize them.

    // ChartData.java
    public class ChartData {
        private Chart chart;
        private List<DataPoint> data;
        // Getters and Setters
        public Chart getChart() { return chart; }
        public void setChart(Chart chart) { this.chart = chart; }
        public List<DataPoint> getData() { return data; }
        public void setData(List<DataPoint> data) { this.data = data; }
    }
    // Chart.java
    public class Chart {
        private String caption;
        private String xaxisname;
        private String yaxisname;
        private String theme;
        // Getters and Setters
    }
    // DataPoint.java
    public class DataPoint {
        private String label;
        private int value;
        // Getters and Setters
    }
  3. Use Gson in your Controller:

    // In your Controller or Service class
    import com.google.gson.Gson;
    // ...
    @GetMapping("/")
    public String showChart(Model model) {
        // 1. Create your data objects
        Chart chartConfig = new Chart();
        chartConfig.setCaption("Monthly Sales Data");
        chartConfig.setXaxisname("Month");
        chartConfig.setYaxisname("Sales");
        chartConfig.setTheme("fusion");
        List<DataPoint> dataPoints = new ArrayList<>();
        dataPoints.add(new DataPoint("Jan", 12));
        dataPoints.add(new DataPoint("Feb", 19));
        dataPoints.add(new DataPoint("Mar", 3));
        dataPoints.add(new DataPoint("Apr", 5));
        dataPoints.add(new DataPoint("May", 2));
        dataPoints.add(new DataPoint("Jun", 3));
        ChartData chartData = new ChartData();
        chartData.setChart(chartConfig);
        chartData.setData(dataPoints);
        // 2. Convert the Java object to JSON
        Gson gson = new Gson();
        String jsonString = gson.toJson(chartData);
        // 3. Add to the model
        model.addAttribute("chartData", jsonString);
        return "index";
    }

This approach is much cleaner, more readable, less prone to errors, and easier to maintain.

Summary

Feature JSP/Servlet Approach Spring Boot / Thymeleaf Approach
Framework Basic Java Web Modern, opinionated framework
Templating JSP (mixes Java/HTML) Thymeleaf (separates logic)
Data Handling Directly in JSP page Controller -> Model -> View
Scalability Good for small apps Excellent for large, complex apps
Recommendation Good for learning or simple projects Recommended for new applications

For any serious project, the Spring Boot with Thymeleaf approach is superior. And within that approach, always use a JSON library like Gson or Jackson to generate your chart data.

分享:
扫描分享到社交APP
上一篇
下一篇