Getting error in jsp while traversing list of string

Viewed 29

I am sending a list of string from my controller to my jsp

model.addAttribute("itemList", Arrays.asList("first", "second"));

And trying to get them in my jsp

<c:forEach var="singleItem" items="${itemList}">
                console.log(${singleItem});
</c:forEach>

But i am getting the following error

jQuery.Deferred exception: first is not defined 
ReferenceError: first is not defined
1 Answers

console.log takes a string. The JS is rendered on the server, and run on the client. ${singleItem} needs to be:

  • In quotes
  • JS-escaped

Look at your rendered page: you will see

console.log(first); 
console.log(second);

JS thinks those are variable references (because in JS, they are).

Just wrapping it in quotes is insufficient, because the string being rendered may have its own quotes, e.g.,

Arrays.asList("first's doodad")

Without JS escaping, and using JS single-quotes:

console.log('${singleItem}');

would render as:

console.log('first's doodad');

which is invalid JS.

Understanding where code is run, and knowing to check the rendered HTML, are important. When rendering into an environment it's important to understand the environment you're rendering in to, same as when rendering HTML into HTML.

Related