You somehow missed the fact that JSP is a HTML/CSS/JS code generator and you expected that JSP EL expressions run "in sync" with JavaScript code embedded in JSP file. This is untrue. JSP/EL runs in webserver, produces HTML/CSS/JS output, basically as one large String
which get sent from webserver to webbrowser, who in turn runs the JSP/EL-produced HTML/CSS/JS output.
An easy way to realize your mistake is doing a rightclick and View Source in webbrowser (on a JSP page containing tags and EL expressions which doesn't throw a server side exception like this, of course). You'll notice that it does actually not contain any single line of JSP/EL code.
Basically, the --count
in your code snippet has only effect in JavaScript, not in JSP, because you basically printed the ${count}
as a JavaScript variable var count
during generating the HTML output. But the value of var count
in JavaScript does in no way affect the value of ${count}
which is used further down in ${valueList.get(count)}
. The ${count}
is still 38 there and has not become 37 or so.
That was the problem. Now we can advance to the solution. I won't post an answer to fix specifically your attempted solution, for the simple reason that this is from high level seen a wrong solution to the underlying problem you tried to solve: converting a Java model object to a JavaScript object.
The right solution to that is converting the Java model object to a string in JSON format in Java side and then letting JSP print it as if it's a JavaScript variable. Your Java model object has also another issue: you seem to have decoupled the X and Y values in two separate lists instead of using a single list with entities in turn having X and Y values.
First create a decent model object:
public class Point {
private int x;
private int y;
// Add/generate constructor+getter+setter+equals+hashcode.
}
Then replace your XValueList
and YValueList
as below:
List<Point> points = new ArrayList<>();
points.add(new Point(1, 2));
points.add(new Point(3, 4));
points.add(new Point(5, 6));
// ...
Then use one of Java JSON APIs to convert this to a JSON string. I'll pick Gson in below example:
String pointsAsJson = new Gson().toJson(points);
Now let JSP print it as if it's a JS variable, the right way:
var data = {data: ${pointsAsJson} };
No need for a clumsy loop here massaging data forth and back.