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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With