Search code examples
jspattributesrequeststrutspagecontext

request attribute and pagecontext attribute in JSP


I have come across a scenario where I have set my attribute in the Action class:

request.setAttribute("itemList", itemList); /* valid List item - confirmed */

and on JSP, I tried to use it within forEach tag as

<c:forEach items="${itemList}" var="individualItem">

<!-- rest of the code -->

It evaluated as a null item. But I added a small scriptlet before this tag:

<% List<MyItem> itemList = (List<MyItem>)request.getAttribute("itemList"); // evaluates as my valid item list 
   List<MyItem> itemList = (List<MyItem>)pageContext.getSession().getAttribute("itemList"); // evaluates as NULL
%>

Does this mean that I am better off using pageContext or session Attribute rather than request Attribute on my front end? Or is there a rule?

KR,


Solution

  • Rule :

    It depends on your requirement, Session keeps data (i.e. variable value) along the entire session (i.e. until the user closes the browser or the session times out), while Request keeps data along a single request , and this includes the situation when the request is redirected or dispatched.

    In your example, pageContext.getSession().getAttribute("itemList") returns null because you set the attribute in the request not the session, but why the EL code returns null, I can't figure it out why..... may be you defined a local variable of name 'itemList' in your jsp which is null , so it reads it first, check answer here