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

SpringBoot+Thymeleaf中切换环境后无法展示Graphviz生成的SVG图像

问题分析与解决方案

核心问题点

  1. Controller未接收环境参数:下拉框提交的target_env参数未被后端捕获,导致createGraph()无法生成对应环境的SVG
  2. SVG数据格式错误:页面直接使用字节数组${graph}拼接data URI,Thymeleaf会输出数组的默认toString(如[B@xxxxxx),而非有效的Base64编码字符串
  3. Data URI类型错误:使用了错误的MIME类型graph/svg,正确的SVG MIME类型应为image/svg+xml
  4. 页面刷新参数异常:meta refresh的content属性存在多余空格,可能导致刷新逻辑异常

修复步骤

1. 修改Controller代码

接收target_env参数,传递给图形生成方法,同时生成正确的Base64编码字符串:

@RequestMapping(value = "/e2emap", method = RequestMethod.GET)
public String getE2E_WebPage(Model model,
        @RequestParam(name = "refreshInterval", required = false) String refreshInterval,
        // 接收target_env参数,设置默认值避免空指针
        @RequestParam(name = "target_env", required = false, defaultValue = "default") String targetEnv) throws IOException {
    // 传入选中的环境,生成对应SVG字节数组
    final byte[] graphBytes = graphGenerator.createGraph(targetEnv);
    // 对字节数组进行Base64编码
    final String graphBase64 = java.util.Base64.getEncoder().encodeToString(graphBytes);

    // 将需要的变量传入视图
    model.addAttribute("graphBase64", graphBase64);
    model.addAttribute("targetEnv", targetEnv);
    // 传入环境列表,渲染下拉选项(替换为你的实际环境集合)
    model.addAttribute("environments", Arrays.asList("dev", "test", "prod"));

    return "Dynamic";
}

2. 修改HTML页面代码

修复img标签的数据源,修正MIME类型,同时优化表单提交逻辑:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
 <meta charset="UTF-8" />
 <link href="../static/css/styles.css" data-th-href="@{/css/styles.css}" rel="stylesheet" />
 <title>SRE End-2-End flow</title>
 <!-- 修复refresh属性的多余空格 -->
 <meta http-equiv="refresh" content="15" />
</head>
<body>
 <div class="title"><a class="a-sre-e2e">SRE End-2-End Flow</a></div>
 <p>
 <form action="/e2emap" method="get">
 <span class="variable-title">Target Environment</span>
 <select class="variable-combobox-values" name="target_env" id="target_env" onchange="this.form.submit()"> 
 <option th:each="env : ${environments}" th:text="${env}" th:selected="${env} == ${targetEnv}">sample-env</option>
   </select>
  </form>
  <h1 th:text="${targetEnv}">bla-bla</h1>
  <span>
  <!-- 使用正确的Base64变量和MIME类型 -->
  <img th:src="@{'data:image/svg+xml;base64,' + ${graphBase64}}" alt="E2E Flow Graph" />
  </span>
</body>
</html>

验证检查

  1. 调试createGraph(targetEnv)方法,确认传入不同环境时能生成对应的SVG字节数组
  2. 在浏览器中查看页面渲染后的img标签src属性,确认是格式正确的data URI(可复制到新标签页验证是否能显示SVG)
  3. 检查浏览器控制台,确认无资源加载或JS错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:15:32