Question

I am new to JSP. I am writing a JSP page named as success.jsp.

In my success.jsp, I am creating a String[] array.

  <%  String[] s={"A","B","C"};
      request.setAttribute("a",s);
   %>
  <br>
 <c:forEach var="x" items="${a}"> 
    <c:out value="${pageScope.x}"/><br>
</c:forEach>

In above JSP page, my doubts are

  1. By default, Why is that String[] array in the "scriptlet" is not created in any of the JSP scopes (i.e., page, request, application)? Hence, I explicitly set that array in request scope.

  2. By default, Why the variable x, is created in the "page scope?"

    What makes situation 1 different from situation 2 ?

Was it helpful?

Solution

  1. Yes, the array in the scriplet is created only in the compiled version of the jsp page, and it is not available in any jsp scope. So you need to grab your array in the desired scope, and then you can use it inside EL, as you did.

  2. The loop variable x is created by the JSTL for loop, so it is already grabbed in the pageScope. The difference between the two situations is that in one case the variable is created by a jsp scriplet, in the other case it is created by a JSTL tag.

Your loop is working, but I think you don't really need to specify to scope of the loop variable x, so you could simplify this way:

<c:forEach var="x" items="${a}">
    <c:out value="${x}"><br/>
<c:forEach>

Or, even better:

<c:forEach var="x" items="${a}">
    ${x}<br/>
<c:forEach>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top