Question

I am unable to retrieve list data from JSTL here is my bean

public class ProjectData {
    public List <String> srNumbers;
    public String comments;

    public String getComments() {
        return comments;
        }
    public List<String> getSrNumbers() {
        return srNumbers;
        }
    }

This is my html snipet

<c:forEach items="${projectDataList}" var="projectDataList">
    <c:forEach items="${projectDataList.srNumbers}" var="srNumbers">
        <c:out value="${srNumbers}" />, 
    </c:forEach>
</c:forEach>

below is what I am setting in the servlet

request.setAttribute("projectDataList", projectDataList);

the expected output is given below

    sr1,sr2,sr3

Defined the setters already

Was it helpful?

Solution

This might work:

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<c:forEach items="${projectDataList}" var="projectDataList">
    ${fn:join(projectDataList.srNumbers.toArray(), ',')}
</c:forEach>

Which avoids a "hanging" comma, which your current code would produce. Not sure about the .toArray() part as I haven't tested the code but an alternative could be to simply add another method to your ProjectData class like:

import  org.apache.commons.lang.StringUtils;

public class ProjectData {
    public List <String> srNumbers;
    public String comments;

    public String getSrNumbersJoined() {
        return StringUtils.join(srNumbers, ",");
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top