SpringBoot项目引入 ECharts 示例

发布于:2025-05-01 ⋅ 阅读:(84) ⋅ 点赞:(0)

1.添加依赖

在项目的 pom.xml 文件中添加 ECharts 的 WebJars 依赖:

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>echarts</artifactId>
    <version>5.4.3</version>
</dependency>

然后在项目根目录下打开终端,运行 mvn clean install 命令来更新依赖。

2.创建后端代码

(1)创建一个控制器类

创建 ChartController 类,用于处理图表数据请求:

package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/chart")
public class ChartController {

    @GetMapping("/data")
    public Map<String, Object> getChartData() {
        // 创建一个包含图表数据和配置的 Map
        Map<String, Object> result = new HashMap<>();
        
        // 设置图表标题
        Map<String, String> title = new HashMap<>();
        title.put("text", "ECharts 示例");

        // 设置图表的系列数据
        Map<String, Object> series = new HashMap<>();
        series.put("name", "销售量");
        series.put("type", "bar");
        series.put("data", new Integer[]{5, 20, 36, 10, 10, 20});

        result.put("title", title);
        result.put("series", series);

        return result;
    }
}

3.创建前端页面

src/main/resources/static 目录下创建一个 index.html 文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ECharts 示例</title>
    <!-- 引入 ECharts -->
    <script src="/webjars/echarts/5.4.3/echarts.min.js"></script>
</head>
<body>
    <!-- 为 ECharts 准备一个具备大小的 DOM -->
    <div id="chart-container" style="width: 600px; height: 400px;"></div>

    <script>
        // 基于准备好的 DOM,初始化 ECharts 实例
        var chart = echarts.init(document.getElementById('chart-container'));

        // 设置图表配置选项
        var option = {
            title: {
                text: 'ECharts 示例'
            },
            tooltip: {},
            legend: {
                data: ['销售量']
            },
            xAxis: {
                data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
            },
            yAxis: {},
            series: [{
                name: '销售量',
                type: 'bar',
                data: [5, 20, 36, 10, 10, 20]
            }]
        };

        // 使用配置项设置图表
        chart.setOption(option);

        // 可以响应浏览器窗口大小变化
        window.addEventListener('resize', function() {
            chart.resize();
        });
    </script>
</body>
</html>

4.运行项目

运行 SpringBoot 应用,访问 http://localhost:8080/index.html 即可看到一个简单的 ECharts 图表。

以上的示例创建了一个简单的柱状图,您可以根据需要修改控制器返回的数据和前端页面中的图表配置,以展示不同类型和样式的图表。

 


网站公告

今日签到

点亮在社区的每一天
去签到