5

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>
0

1 Answer 1

10

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.