Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access array list in jsp , if i pass bean

I am new to JSTL. How can i use JSTL <c:foreach> inside jsp if i pass below sample bean

class B{
    private String value="";
    private ArrayList arrayVals;
    public String getvalue(){
        return value;
    }
    public String getarrayVals(){
        return arrayVals;
    }
}

I will pass Bean "B" only. I tried like below, but jsp not compiled. Please help me.

<c:forEach items="${B.getarrayVals}" var="book"> 
    <c:out value="{book.title}"/> 
</c:forEach>
like image 207
pradeep cs Avatar asked Mar 05 '11 09:03

pradeep cs


1 Answers

First of all, getarrayVals() should be spelt getArrayVals(), and it should return a List, not a String, obviously.

Now suppose the servlet or action sets an attribute "b" of type B like this :

request.setAttribute("b", theBInstance);

and then forwards to a JSP, you can access the list in the attribute "b" like this:

${b.arrayVals}

You must refer to the B instance by the name of the request attribute, not by its class name. If you name the attribute foo, then use must use ${foo.arrayVals}. This will simply print to toString of the list. If you want to get the element at index 3 of the list, you can use

${b.arrayVals[3]}

And if you want to iterate over the list elements, use the c:forEach construct:

<c:forEach items="${b.arrayVals}" var="element">
    The element value is ${element} <br/>
</c:forEach>
like image 187
JB Nizet Avatar answered Oct 14 '22 13:10

JB Nizet