CoachJon
CoachJon

Reputation: 77

How to copy multidimensional array from Java request variable to Javascript variable in a JSP page?

I need to get the contents of a multidimensional array, passed in as a String [][] saved in a request variable, and put its contents in a Javascript variable.

The "String [][] dataArray" variable holds the values I expect. Example:

dataArray[0][0] = "Joe"

dataArray[0][1] = "Smith"

dataArray[0][2] = "901-555-1212"

dataArray[1][0] = "Jane"

dataArray[1][1] = "Smith"

dataArray[1][2] = "901-555-9999"

This doesn't work:

Java

request.setAttribute("passedInArray", dataArray);

Javascript (inside JSP page)

var jsArray = <%= request.getAttribute("passedInArray");%>

How can I get the contents of passedInArray into jsArray? Thanks in advance!

Upvotes: 1

Views: 1756

Answers (1)

Tap
Tap

Reputation: 6522

If you need to use a String[][], you would need to iterate over the rows in passedInArray on the server side.

var dataArray = new Array();

<c:forEach var="row" items="${passedInArray}">
    dataArray.push(['${row[0]}', '${row[1]}', '${row[2]}']);
</c:forEach>

An alternative would be to serialize your array into a JSON string. There are good java libraries like Jackson and Gson available for the job. Basically, they would be accomplishing the same as if you were to code it like this:

    StringBuffer sb = new StringBuffer("[");
    for (int i = 0; i < dataArray.length; i++) {
        sb.append("[");
        for (int j = 0; j < dataArray[i].length; j++) {
            sb.append("'" + dataArray[i][j] + "'");
            if (j < dataArray[i].length-1)
                sb.append(',');
        }
        sb.append("]");
        if (i < dataArray.length-1)
            sb.append(',');
    }       
    sb.append("]");
    request.setAttribute("passedInArray", sb.toString());

Then in your jsp, you would just declare it as a javascript variable and use it:

    var dataArray = ${passedInArray};
    console.log(dataArray.length);
    console.log(dataArray[0].length);

No matter how you do it, you need to do work on the server side to transform your java array into String(s) that javascript can use directly.

Upvotes: 2

Related Questions