背景故事:我正在创建一个网页,以条形图格式显示整个月内服务器的每日访问计数。
库/技术:
- Spring Boot - 用于 MVC 后端
- .JSP - 用于实际的网页布局
- D3 Javascript - 用于创建图形元素
- Tomcat - 用于运行整个困惑
因此,我已将数据收集到页面 Controller 的整数数组中,并将其传递给 JSP 页面脚本部分中的变量。我遇到的问题是,如果我将 .JSP 作为 int 数组传递,则 .JSP 会抛出“非法字符”错误,或者如果我将其作为 int 数组传递,则会抛出“元素列表后缺少 ]”错误将其作为字符串数组传递。
此时具体的错误对我来说并不重要。我只是在研究如何将数据(最好作为 int 数组)传递到脚本变量中,以便我可以将其传递给 D3 代码进行绘图。
以下是数据如何从 Controller 代码传递到 .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);
任何和所有帮助将不胜感激
最佳答案
是否可以从 Controller 传递列表而不是数组?在这种情况下,整数列表 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));
关于javascript - 将 Java 数组从 Spring MVC Controller 传递到 JSP 脚本 var 变量抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60326216/