Alexa
Alexa

Reputation: 81

How to access a List from the jsp to Javascript

I am trying to transfer a list passed from the Controller (to the jsp), and pass the said list from the jsp to javascript.

The data on the list should replace the values of X (the date) and Y.

var data = {
    values:[
        { X: "8/7/12",  Y: 21 },
        { X: "8/8/12",  Y: 32 },
        { X: "8/9/12",  Y: 62 },
        { X: "8/10/12", Y: 8  },
        { X: "8/11/12", Y: 40 },
        { X: "8/12/12", Y: 12 },
        { X: "8/13/12", Y: 14 },
        { X: "8/14/12", Y: 72 },
        { X: "8/15/12", Y: 11 },
        { X: "8/16/12", Y: 98 },
    ]};



The list I wish to pass contains the following:
1. the String version of LocalDate (Jodatime) - for the X axis
2. the scores - for the y-axis

I have seen and tried a couple of solutions based on situations in various forums online, but none of them worked the way it was intended to. I also tried passing parallel arrays but none of them seemed to work.

Upvotes: 0

Views: 4906

Answers (2)

Tap
Tap

Reputation: 6522

In this kind of situation, I prefer to serialize the Java List object into a JSON string in the controller, and pass that string to the jsp. Assuming your list contains instances of a class that looks like this,

public class MyObject {
    protected String X;
    protected int Y;

    // getters, setters, other methods and fields...
}

You can use libraries like Gson or Jackson to serialize the list in your controller.

List<MyObject> list = new ArrayList<MyObject>();
// add some objects to the list...

String json = new Gson().toJson(list);
request.setAttribute("values", json);

In your jsp, the values request attribute is a string representing a complete javascript object in JSON.

var data = {
    values: ${values}
};

Upvotes: 1

Darshan Lila
Darshan Lila

Reputation: 5868

You can simply do this from JSP to Javascript

var data = { values:[
        { X: <%=x[0]%>, Y: <%=y[0]%> },
        { X: <%=x[1]%>, Y: <%=y[1]%> },
        ...
    ]};

Note here I have use array of X and Y for values, you can use any data structure into jsp and later get it into javascript.

Alternatively If you are passing the data from controller to jsp you can use JSTL to iterate through the data and pass it to javascript.

Upvotes: 0

Related Questions