Search code examples
javajspjsp-tags

How to use a variable value in items attribute of c:forTokens and c:forEach


I have a jsp page which will read data from a text file, and will format it in tabular form.

The content returned from the text file into JSP is like:

ABC:::XYZ:::POR:::STV
asd:::fgh:::hjk:::lkj
zxc:::cvb:::nmn:::aaa

JSP PAGE:

<%! String content = MyFileReader.readData()); %>
<c:forTokens items="ABC:::XYZ:::POR:::STV" delims="::::" var="name">
<c:out value="${name}"/><br>
</c:forTokens>

Instead of items="ABC:::XYZ:::POR:::STV", I want to use content variable in items attribute. items="${content}" is not working for me.


Solution

  • Local variables declared in <% scriptlets %> or class members <%! ... %> are not part of EL scope. You need to move this value to either page request session or application scope, for instance using

    <c:set scope="page" value="<%=content %>" var="value"/>
    

    and then access it via ${value} like

    <c:forTokens items="${value}" delims="::::" var="name">
        <c:out value="${name}" /><br />
    </c:forTokens>