Reputation: 2517
In my servlet I have stored the session variables as follows,
for(int i=0;i>pageNames.length;i++) {
session.setAttribute("pageNames["+i+"]",pageNames[i]);
}
Now from the JSP page I created a javascript function as follows,
for(var i=0;i<10;i++) {
var pageNames = '<%=session.getAttribute("pageNames["+i+"]")%>';
alert(pageNames);
}
But when I execute the code an error saying, unknown variable 'i' is dispalyed within
var pageNames = '<%=session.getAttribute("pageNames["+i+"]")%>';
How could be this possible when I have written it within the for loop with 'var i' defined? Can anyone tell me how to access the session variables stored as 'pageNames[0],pageNames[1],pageNames[2].......' from my javascript??? Thanks in advance.
Upvotes: 2
Views: 671
Reputation: 2070
You are mixing two worlds - the javascript and jsp. The JSP, with your javascript code, have to be translated into java servlet first. But the java servlet is not aware of the javascript loop. The JSP is interpreted before the javascript can be recognized, so you cannot use the loop variable i
.
My suggestion is to first prepare an array of page names from JSP and then iterate over it in javascript. That is something like:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<script>
var pageNames = new Array(
<c:forEach var="i" begin="1" end="10" varStatus="status">
<c:set var="pageIndex">pageNames[${i}]</c:forEach>
"${sessionScope[pageIndex]}"
<c:if test="${!status.last}" >, </c:if>
</c:forEach>);
for(var i=0;i<pageNames.length;i++) {
alert(pageNames[i]);
}
</script>
Anyway, much better approach would be to store the whole list of page names into session and iterate over the stored list.
Upvotes: 3
Reputation: 301
I cant comment on your post due to low reputation hence I am writing this.
session is used to store user related data on the server so that our server can remember the user. JSP is client side so, session will not be available there.
Why dont you use request.setAttribute in java page and access it on the JSP using request.getAttribute method.
Upvotes: 4