java - jsp中如何从 Controller 获取json数据?

标签 java json d3.js

我想将 json 数据填充到 d3 图表中。但是如何从 Controller 获取json数据呢? 这里rootVO是json文件,我正在传递给jsp,但我不知道如何收集它并在jsp中使用它?

Controller 类

@RequestMapping("/sunburst")
public String sunburstChart(Model model)
{
    model.addAttribute("jsonData", rootVO);
    return "sunburstChart";
}

我调用该方法的另一个 jsp 文件

$.ajax
({
    url: "sunburst", 
    async: false, 
    success: function(data) 
    { 
        console.log(data); 
        $("#sunburstChart").append(data);
    }
});

这是我的 sunburstChart.jspin,我想要 json 数据

<!DOCTYPE html>
<head>
    <title>Sunburst Tutorial (d3 v4), Part 3</title>
    <script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<style>
@import url('https://fonts.googleapis.com/css?family=Raleway');

body {
  font-family: "Raleway", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
</style>
<body>
    <svg></svg>
    <label><input class="sizeSelect" type="radio" name="mode" value="size" checked /> Size</label>
    <label><input class="sizeSelect"  type="radio" name="mode" value="count" /> Count</label>
</body>

<script>

    // Variables
    var width = 500;
    var height = 500;
    var radius = Math.min(width, height) / 2;
    var color = d3.scaleOrdinal(d3.schemeCategory20b);
    var sizeIndicator = "size";
    var colorIndicator = "sentiment";

    // Size our <svg> element, add a <g> element, and move translate 0,0 to the center of the element.
    var g = d3.select('svg')
        .attr('width', width)
        .attr('height', height)
        .append('g')
        .attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');


    // Create our sunburst data structure and size it.
    var partition = d3.partition()
        .size([2 * Math.PI, radius]);


    // Get the data from our JSON file
    d3.json(
         $.ajax
        ({
            type:"GET",
            dataType : 'json',
            url : '/sunburst',
            success : function(response) 
            {

            },
            error: function() {
                alert("asda");
            }
        });
        , function(error, nodeData) {
        if (error) throw error;


        // Find the root node, calculate the node.value, and sort our nodes by node.value
        var root = d3.hierarchy(nodeData)
            .sum(function (d) { return d.size; })
            .sort(function(a, b) { return b.value - a.value; });


        // Calculate the size of each arc; save the initial angles for tweening.
        partition(root);
        arc = d3.arc()
            .startAngle(function (d) { d.x0s = d.x0; return d.x0; })
            .endAngle(function (d) { d.x1s = d.x1; return d.x1; })
            .innerRadius(function (d) { return d.y0; })
            .outerRadius(function (d) { return d.y1; });


        // Add a <g> element for each node; create the slice variable since we'll refer to this selection many times
        var slice = g.selectAll('g')
            .data(root.descendants())
            .enter().append('g').attr("class", "node");


        // Append <path> elements and draw lines based on the arc calculations. Last, color the lines and the slices.
        slice.append('path').attr("display", function (d) { return d.depth ? null : "none"; })
            .attr("d", arc)
            .style('stroke', '#fff')
            .style("fill", function (d) { return color((d.children ? d : d.parent).data.name); });


        // Populate the <text> elements with our data-driven titles.
        slice.append("text")
            .attr("transform", function(d) {
                return "translate(" + arc.centroid(d) + ")rotate(" + computeTextRotation(d) + ")"; })
            .attr("dx", "-20")
            .attr("dy", ".5em")
            .text(function(d) { return d.parent ? d.data.name : "" });


        // Redraw the Sunburst Based on User Input
        d3.selectAll(".sizeSelect").on("click", function(d,i) {

            // Determine how to size the slices.
            if (this.value === "size") {
              root.sum(function (d) { return d.size; });
            } else {
              root.count();
            }

            partition(root);

            slice.selectAll("path").transition().duration(750).attrTween("d", arcTweenPath);
            slice.selectAll("text").transition().duration(750).attrTween("transform", arcTweenText);
        });
    });


    /**
     * When switching data: interpolate the arcs in data space.
     * @param {Node} a
     * @param {Number} i
     * @return {Number}
     */
    function arcTweenPath(a, i) {

        var oi = d3.interpolate({ x0: a.x0s, x1: a.x1s }, a);

        function tween(t) {
            var b = oi(t);
            a.x0s = b.x0;
            a.x1s = b.x1;
            return arc(b);
        }

        return tween;
    }

    /**
     * When switching data: interpolate the text centroids and rotation.
     * @param {Node} a
     * @param {Number} i
     * @return {Number}
     */
    function arcTweenText(a, i) {

        var oi = d3.interpolate({ x0: a.x0s, x1: a.x1s }, a);
        function tween(t) {
            var b = oi(t);
            return "translate(" + arc.centroid(b) + ")rotate(" + computeTextRotation(b) + ")";
        }
        return tween;
    }


    /**
     * Calculate the correct distance to rotate each label based on its location in the sunburst.
     * @param {Node} d
     * @return {Number}
     */
    function computeTextRotation(d) {
        var angle = (d.x0 + d.x1) / Math.PI * 90;

        // Avoid upside-down labels
        return (angle < 120 || angle > 270) ? angle : angle + 180;  // labels as rims
        //return (angle < 180) ? angle - 90 : angle + 90;  // labels as spokes
    }

</script>

最佳答案

您无法按照您显示的方式发送 json-data 并实现您想要的效果。 为此,您可以按照下面提到的任何一项操作:

  1. 读取 json 文件,反序列化为 POJO,然后从单独的 Controller 端点发送反序列化数据。确保在文档就绪状态下从客户端调用 ajax 方法。
  2. 读取您的 json 文件,反序列化为 POJO,然后使用 modelAttribute 发送,就像您所做的那样,即 model.addAttribute("jsonData", deserialzedData); 并通过 JS 从 Controller 端读取,例如:var yourJsonData=${jsonData},使用 JSON.parse(yourJsonData) 解析为 jsonData,然后将其用于您的图表。

但请确保,所有事件(例如页面加载然后根据此数据生成图表)都按照所需的顺序依次发生。 P.S.:如果发现困难,请搜索读取json文件并映射到pojo。 如果您不确定或需要更多帮助,请说明您的 json 文件数据结构和您的具体问题。我会尽力提供帮助

关于java - jsp中如何从 Controller 获取json数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58086873/

相关文章:

svg - 有没有办法在 d3 中为饼图添加高亮显示?

javascript - Y 轴已创建但不可见

java.io.Exception com.android.okhttp 上的流意外结束

java - 使用 Java 和 JSNI 的 JSON 对象的名称/值对循环

c - 使用 json 在 ibmiot cloud 中发布事件

javascript - 如果div的文本与另一个div相同,如何删除它?

java - 使用 Spring 在 Java 中进行批处理的输入文件中的多种模式

java - Deflater.deflate 和小输出缓冲区

java - 代码在导出后不起作用,但在导出之前起作用

json - 将 JSON 数据映射到具有特定 View 模型类型的 Knockout observableArray