Nitro
Nitro

Reputation: 624

Passing a java array and use it in a spring view

I am having some troubles with how to pass variables in spring.

My intention is to pass an double array and to use this to create a google visualization by using the array in javascript.

The problem is that I only get the java object (toString), and I'm not able to loop over the values.

Java file.

double[] array = generateArray();

return new ModelAndView("array", "array", array);

And in my jsp

dataTable = new google.visualization.DataTable();
var data = '${array}';

dataTable.addColumn('string', 'Task');
dataTable.addColumn('number', 'Hours');
dataTable.addRows(data.length);

for (i=0;i<=data.length;i++)
{
    dataTable.setValue(i, data[i]);
}


var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240, is3D: true, title: 'My Array'});

What I want is to be able to loop over the array here. I know I could use Arrays.Tostring(), but this seems unneccesary.

Upvotes: 3

Views: 2116

Answers (2)

JB Nizet
JB Nizet

Reputation: 691685

The toString method of a double array returns something like this : [D@bfbdb0. So, you need to call a function which iterates on the array and prints out the array as a Javascript array.

Or you can do it with the JSTL :

var data = [<c:forEach var="d" items="${array}">${d}, </c:forEach>];

Upvotes: 0

axtavt
axtavt

Reputation: 242686

Using JSTL (requires taglib declaration <%@taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>):

var data = '<c:forEach var = "a" items = "${array}" varStatus = "s">${a}${s.last ? "" : ","}</c:forEach>';

Upvotes: 2

Related Questions