Skip to content Skip to sidebar Skip to footer

Set Array Values In Javascript From Jstl Code

I have a code that looks like this: In AnalyzeUserClient.jsp: <%= (ArrayList)request.getSession().getAttribute('arrayList') %><

Solution 1:

Don't mix EL and scriptlets. In fact, forget about scriptlets completely:

var sessionId = [];
<c:forEach items="${sessionScope.arrayList}"var="id">
    sessionId.push("${id}"); 
</c:forEach>

Note though that this will generate invalid JavaScript if one of the IDs happens to contain a double quote. So you'd better JavaScript-escape the IDs before, in your controller. And I would suggest a completely different approach: serialize the list of IDs to a JSON string in your controller, and store this JSON string in request attribute. The JSP page will just need

var sessionId = ${jsonEncodedSessionIds};

which will translate to the following generated code:

var sessionId = ["id1", "id2"];

Post a Comment for "Set Array Values In Javascript From Jstl Code"