Search code examples
struts2ognl

How to read List object in JSP using OGNL tags


My requirement is to read Objects of List from Session in JSP using OGNL.

In my action class,

Employee emp1 = new Employee();
emp1.setName("xyz");

Employee emp2 = new Employee();
emp2.setName("123");


ArrayList list = new ArrayList();
list.add(emp1);
list.add(emp2);

session.setAttribute("listObj", list);

So am trying to check name in Jsp pseudo code ::

`IF TEST ="#session.list.get(0).getName()"=="xyz"
print :: xyz user.
ElSE
   print :: guest user..`

Thanks Rajesh


Solution

  • Your pseudo code is here.

    IF TEST ="#session.list.get(0).getName()"=="xyz"
    print :: xyz user.
    ElSE
    print :: guest user..
    

    The listObj is actually session-scoped attribute. So you access it in two ways:

    1. #session.objectname or
    2. #session['objectname']

    You can use equals() method for comparing strings.

       <s:if test="%{#session.listObj.get(0).getName().equals("xyz")}">
           <h2>xyz user</h2> 
       </s:if>
       <s:else>
           <h2>guest user</h2>          
       </s:else>