You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Java后端参数传递至HTML以生成Google Chart图表

解决方案:Java后端数据传递到前端Google Chart

我来给你梳理几个可行的方案,帮你把后端的统计数据顺利传到前端的Google Chart里,同时也会提一下HTML路径的相关注意事项:

方案一:后端模板引擎渲染(适合HTML由后端直接返回的场景)

如果你的项目是Spring Boot这类框架,推荐用Thymeleaf这类模板引擎,直接在后端把数据注入到HTML页面中:

步骤1:调整后端代码

首先把你现有的status()方法改成返回模板视图,同时把数据放到Model里(注意把Map的键改成更规范的格式,去掉空格和冒号,方便前端调用):

@GetMapping("/status-page")
public ModelAndView statusPage() {
    ModelAndView mav = new ModelAndView("status"); // 对应templates下的status.html
    long countByXmlSuccessResult = statusRepository.countByXmlSuccessResult();
    long countByXmlErrorResult = statusRepository.countByXmlErrorResult();
    long countByJsonSuccessResult = statusRepository.countByJsonSuccessResult();
    long countByJsonErrorResult = statusRepository.countByJsonErrorResult();
    
    mav.addObject("xmlSuccess", countByXmlSuccessResult);
    mav.addObject("xmlError", countByXmlErrorResult);
    mav.addObject("jsonSuccess", countByJsonSuccessResult);
    mav.addObject("jsonError", countByJsonErrorResult);
    return mav;
}

步骤2:修改前端HTML(以Thymeleaf为例)

把HTML文件放到Spring Boot的src/main/resources/templates目录下,然后在script里用模板变量替换原来的硬编码数值:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['XML Success', [[${xmlSuccess}]]],
['XML Error', [[${xmlError}]]],
['JSON Success', [[${jsonSuccess}]]],
['JSON Error', [[${jsonError}]]]
]);
var options = {
title: 'My Daily Activities',
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
<div id="donutchart" style="width: 900px; height: 500px;"></div>

访问路径就是http://localhost:8080/status-page,后端会直接渲染好带数据的HTML返回。

方案二:前端AJAX异步请求API(适合前端是静态HTML的场景)

如果你的HTML是静态文件(比如放在src/main/resources/static下),可以让前端通过AJAX请求你现有的REST接口,拿到数据后再渲染图表:

步骤1:优化后端接口的键名

先把你现有的status()方法里的Map键改成更规范的格式,避免空格和特殊字符:

public ResponseEntity<Map<String,Object>> status() {
    Map<String,Object> map = new HashMap<String,Object>();
    long countByXmlSuccessResult = statusRepository.countByXmlSuccessResult();
    long countByXmlErrorResult = statusRepository.countByXmlErrorResult();
    long countByJsonSuccessResult = statusRepository.countByJsonSuccessResult();
    long countByJsonErrorResult = statusRepository.countByJsonErrorResult();
    // 改成规范的键名
    map.put("xmlSuccess", countByXmlSuccessResult);
    map.put("xmlError", countByXmlErrorResult);
    map.put("jsonSuccess", countByJsonSuccessResult);
    map.put("jsonError", countByJsonErrorResult);
    return new ResponseEntity<Map<String,Object>>(map, HttpStatus.OK);
}

步骤2:修改前端HTML的图表渲染逻辑

用fetch API请求后端的/status接口,拿到数据后再生成图表:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);

async function drawChart() {
    // 先请求后端接口拿数据
    const response = await fetch('/status');
    const stats = await response.json();
    
    var data = google.visualization.arrayToDataTable([
    ['Task', 'Hours per Day'],
    ['XML Success', stats.xmlSuccess],
    ['XML Error', stats.xmlError],
    ['JSON Success', stats.jsonSuccess],
    ['JSON Error', stats.jsonError]
    ]);
    var options = {
    title: 'My Daily Activities',
    pieHole: 0.4,
    };
    var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
    chart.draw(data, options);
}
</script>
<div id="donutchart" style="width: 900px; height: 500px;"></div>

如果HTML放在static目录下,比如文件名叫chart.html,访问路径就是http://localhost:8080/chart.html,页面会自动请求/status接口获取数据。

关于HTML路径的注意事项

  • 如果用模板引擎(方案一):HTML文件要放在src/main/resources/templates目录下,通过后端控制器的@GetMapping映射路径访问。
  • 如果是静态HTML(方案二):HTML文件放在src/main/resources/static目录下,直接通过文件名访问即可(比如/chart.html)。

内容的提问来源于stack exchange,提问作者Alice Cho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:02:39