如何把流程图导出为 SVG 供前端展示?

解读

在国内企业级 Java 面试中,Struts 虽然已不再是主流,但**“老系统维护”与“技术债重构”场景依旧高频。面试官抛出“流程图导出 SVG”并非考察你是否会画流程图,而是验证你对 Struts 请求生命周期、结果类型扩展、拦截器链与前端静态资源分离方案的综合掌握。核心痛点是:Struts 默认结果类型(dispatcher、redirect、stream)都不直接输出 SVG,必须自定义结果类型并解决中文乱码、缓存策略、安全头**三大落地问题。

知识点

  1. Struts 结果类型(Result Type)扩展机制:通过实现 Result 接口或继承 StrutsResultSupport,在 struts.xml 中注册新类型。
  2. SVG 本质:可读写 XML,MIME 必须为 image/svg+xml,输出前需设置 Content-Type、Content-Disposition、Cache-Control。
  3. 拦截器链与生命周期:在 PreResultListener 里可对 Model 中的流程图对象做最后加工,避免在 Action 中耦合 IO。
  4. 前端跨域与缓存:国内网关层(Nginx/OpenResty)常加 X-Content-Type-Options: nosniff,Struts 端必须同步添加,否则 SVG 被误判下载。
  5. 生产安全:SVG 内可嵌 script,必须过滤危险标签(script、foreignObject)后再输出,符合国内等保 2.0 对 XSS 的检测要求。

答案

步骤一:定义 FlowSvgResult 继承 StrutsResultSupport

public class FlowSvgResult extends StrutsResultSupport {
    @Override
    protected void doExecute(String location, ActionInvocation ai) throws Exception {
        HttpServletResponse resp = ServletActionContext.getResponse();
        resp.setContentType("image/svg+xml;charset=UTF-8");
        resp.setHeader("Content-Disposition", "inline;filename=flow.svg");
        resp.setHeader("Cache-Control", "max-age=3600,s-maxage=3600");
        resp.setHeader("X-Content-Type-Options", "nosniff");

        // 从 Action 里取已生成的 SVG 字符串
        String svg = (String) ai.getStack().findValue("svgXml");
        // 国内习惯用 WAF,先脱敏
        svg = svg.replaceAll("(?i)<script.*?</script>", "")
                 .replaceAll("(?i)<foreignObject.*?</foreignObject>", "");
        resp.getWriter().write(svg);
    }
}

步骤二:在 src/main/resources/struts.xml 注册

<package name="flow" extends="struts-default">
    <result-types>
        <result-type name="svg" class="com.xxx.result.FlowSvgResult"/>
    </result-types>
    <action name="exportFlow" class="com.xxx.action.FlowAction">
        <result name="success" type="svg"/>
    </action>
</package>

步骤三:Action 侧只负责把流程图序列化为 SVG 字符串

public class FlowAction extends ActionSupport {
    private String svgXml;   // 提供 getter
    public String execute(){
        svgXml = FlowChartEngine.toSvg(model); // 内部用 bpmn-js 或 mxGraph
        return SUCCESS;
    }
}

步骤四:前端调用

// Vue/React 通用
fetch('/exportFlow?processId=123')
  .then(r => r.text())
  .then(svg => document.getElementById('flowDiv').innerHTML = svg);

至此,零文件落地、高并发安全、符合国内等保 的 SVG 导出方案完成。

拓展思考

  1. 若流程图过大,可考虑 服务端 gzip(Struts 的 struts.i18n.encoding 已设 UTF-8,再加 filter 对 image/svg+xml 启 gzip)与 HTTP 206 分片,降低内网带宽。
  2. 老系统仍用 Struts 2.3.x,存在 S2-045 等历史漏洞,上线前务必升级至 2.5.30 以上,并把导出路径加入 struts.action.excludePattern,避免 OGNL 注入。
  3. 如果未来迁移到 Spring Boot,可把 FlowSvgResult 抽象成 @RestController 的 ResponseEntity<Resource>,但自定义结果类型的思想依旧通用,可平移到 Spring 的 HttpMessageConverter。