如何在 jsp 中从控制器获取 json 数据?



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

控制器类

@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 数据并实现您想要的。 为此,您可以遵循以下任何一项:

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

但请确保所有事件(如页面加载然后从此数据生成图表(都按所需顺序一个接一个地发生。 PS:搜索读取json文件并映射到pojo,如果你发现困难。 如果您不确定或需要更多帮助,请说明您的 json 文件数据结构和您的特定问题。我会尽力帮忙