[英]Passing an Java array from Spring MVC controller to a JSP script var variable throwing error
背景故事:我正在創建一個網頁,該網頁以條形圖格式顯示整個月內對服務器的每日訪問次數。
圖書館/技術:
所以我在頁面控制器中的一個整數數組中收集了數據,並將其傳遞給 JSP 頁面腳本部分中的一個變量。 我遇到的問題是,如果我將它作為 int 數組傳遞,則 .JSP 會拋出“非法字符”錯誤;如果我將其作為字符串數組傳遞,則會引發“元素列表后缺少 ]”錯誤。
在這一點上,具體的錯誤對我來說並不重要。 我只是想看看如何將數據(最好是一個 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
這實際上是導致錯誤的變量
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.