Iterating over ArrayList with c: foreach (JSP / JSTL), variable not working

There are tons of examples for my problem, I know, but I've gone through many of them and can't figure out where my mistake is.

I am iterating over ArrayList (TestSzenario). The TestSzenario class contains a named String variable with correct getters and setters.

Here's my code:

<td><select name="selectSzenario" id="selectSzenario" size="1">
                <c:forEach items="<%=testszenario.getSzenariosForSummary() %>" var="szenario"> 
                    <option>${szenario.name}</option>
                </c:forEach></select></td></tr>

      

My problem is that the variable is not working. I am getting $ {szenario.name} for each parameter in the select box. I have described the JSTL-taglib correctly, and since there are several options on the site, I know that iteration works. Also I looked in the HTML source code which is allowed for foreach.

HTML output:

        <tr><td>Szenario:</td>
        <td><select name="selectSzenario" id="selectSzenario" size="1">

                    <option>${szenario.name}</option>

                    <option>${szenario.name}</option>
                </select></td></tr>

      

EDIT for answer 1: Thanks, but I've tried this before:

ArrayList<TestSzenario> szenarioList = testszenario.getSzenariosForSummary();
request.setAttribute("aList", szenarioList);
request.setAttribute("ts", testszenario);

<c:forEach items="${aList}" var="szenario">
<option>${szenario.name}</option>
</c:forEach></select></td></tr>

<c:forEach items="${ts.szenariosForSummary}" var="szenario">
<option>${szenario.name}</option>
</c:forEach></select></td></tr>

      

But in any case it doesn't even iterate over the list, and only one option appears as a result (the list contains 2 elements).

+3


source to share


1 answer


<%=testszenario.getSzenariosForSummary() %>

converts the object to String

using a method String#valueOf(Object)

and writes it directly to the HTTP response. This is not what you want. Moreover, you should not mix oldschool scripts with modern taglibs / EL at all.

You need to make sure testszenario

EL is available ${}

. So, just set it as a Page, Request, Session or Application Scope attribute in advance in some kind of Servlet like

request.setAttribute("testszenario", testszenario);

      

Then you can just access it in the normal way:

<c:forEach items="${testszenario.szenariosForSummary}" var="szenario"> 

      

See also:




Refresh . As for the problem where EL is not being interpreted, you apparently have a mismatch between the JSTL version and the container / web.xml

. Make sure the versions are correctly aligned. For example. Servlet container 3.0, version="3.0"

in web.xml

, JSTL 1.2. See also our JSTL wiki page.

See also:



  • Our JSTL Wiki page - read the "Help! Expression Language (EL, those ${}

    ) doesn't work in my JSTL tags!"
+8


source







All Articles