背景故事:我正在创建一个网页,以条形图格式显示整个月内对服务器的每日访问次数。
图书馆/技术:
- Spring Boot-用于MVC后端
- .JSP-用于实际的网页布局
- D3 Javascript-用于创建图形元素
- Tomcat-用于运行整个混乱
因此,我已经在页面控制器中的interger数组中收集了数据,并将其传递给JSP页面脚本部分中的一个变量。我遇到的问题是,如果我将其作为int数组传递,JSP会抛出"非法字符">错误;如果我将它作为字符串数组传递,则JSP会在element-list"之后抛出<em]"错误。>
在这一点上,具体的错误对我来说并不重要。我只是在研究如何将数据(最好是作为int数组(传递到脚本变量中,以便将其传递给D3代码进行绘图。
以下是如何将数据从控制器代码传递到JSP页面
//converting from list to array and translating to string if int array is impossible
index = 0;
String[] graph1Data = new String[dailyCount.size()];
for(int i : dailyCount) {
graph1Data[index] = dailyCount.get(index).toString();
log.info(index + " = " + graph1Data[index]);
index++;
}
//passing data to the JSP page
mav.addObject("serverName", serverInstance.getName());
mav.addObject("month",month);
mav.addObject("hostItems", hostItems);
mav.addObject("totals", totalItems);
mav.addObject("graph1Data", graph1Data);
return mav;
这是我获取传递数据并尝试将其分配给脚本变量的代码
//java script code above
document.getElementById("defaultOpen").click();
var src = ${graph1Data}); //<<-- attempting to assign to script variable
var msvg = d3.select("#mGraph"),
margin = 100,
width = msvg.attr("width") - margin,
height = msvg.attr("height") - margin;
var data = [10, 50, 15, 30, 20]; //<<-- what the passed data will replace
//more D3 graphing code below
这就是导致错误的变量中的实际结果
- int数组-
var src = [I@be6d99b);
- 字符串数组-
var src = [Ljava.lang.String;@d0baa7f);
如有任何帮助,将不胜感激
是否可以从控制器传递列表而不是数组?在这种情况下,整数列表toString((方法将生成与javascript数组语法相同的字符串。
对于字符串列表,有必要为每个字符串添加引号,以实现与javascript中相同的语法。例如:
String[] graph1Data = new String[dailyCount.size()];
for(int i : dailyCount) {
// adding quotation marks
graph1Data[index] = "'" + dailyCount.get(index).toString() + "'";
log.info(index + " = " + graph1Data[index]);
index++;
}
// convert array to list when adding it to model-and-view
mav.addObject("graph1Data", Arrays.asList(graph1Data));