6

is it possible to add values to an ArrayList instead of using a HashMap

something like:

<jsp:useBean id="animalList" class="java.util.ArrayList" />

<c:set target="${animalList}" value="Sylvester"/>

<c:set target="${animalList}" value="Goofy"/>

<c:set target="${animalList}" value="Mickey"/>

<c:forEach items="${animalList}" var="animal">

${animal}<br>

</c:forEach>    

now getting the error:

javax.servlet.jsp.JspTagException: Invalid property in &lt;set&gt;:  "null"

thx

Michel
  • 9,220
  • 13
  • 44
  • 59

3 Answers3

11

JSTL is not designed to do this kind of stuff. This really belongs in the business logic which is (in)directly to be controlled by a servlet class.

Create a servlet which does like:

protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    List<String> animals = new ArrayList<String>();
    animals.add("Sylvester");
    animals.add("Goofy");
    animals.add("Mickey");
    request.setAttribute("animals", animals);
    request.getRequestDispatcher("/WEB-INF/animals.jsp").forward(request, response);
}

Map this on an url-pattern of /animals.

Now create a JSP file in /WEB-INF/animals.jsp (place it in WEB-INF to prevent direct access):

<c:forEach items="${animals}" var="animal">
    ${animal}<br>
</c:forEach>

No need for jsp:useBean as servlet has already set it.

Now call the servlet+JSP by http://example.com/context/animals.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • is it possible to run the c:foreach on an ArrayList() that is not scoped to page, session, etc? For instance, if the arraylist was a property in a class with a getter/setter. –  Mar 22 '11 at 17:45
  • 2
    @robert: Certainly. Just put that class in the scope and use `items="${bean.list}"` where `${bean}` points to that class which has a `getList()` method returning the list. – BalusC Mar 22 '11 at 17:45
3

To do add() to a List or others methods from Map, Set, etc... You have to use a unusable variable.

<jsp:useBean id="list" class="java.util.ArrayList"/>
<c:set var="noUse" value="${list.add('YourThing')}"/>
<c:out value="${list}"/>
Asaph
  • 159,146
  • 25
  • 197
  • 199
2

The above code is not working.

Following are the lines of code that has to be placed in file animals.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:forEach var="animal" items="${animals}">
   <c:set var="animalName" value="${animal}"/>
   <c:out value="${animalName}"/>
</c:forEach>
StKiller
  • 7,631
  • 10
  • 43
  • 56
Sarvesh
  • 37
  • 1
  • 4
    The OP was already using JSTL, it was unnecessary to mention it in my answer. It's obvious enough that the taglib has to be declared in order to get the tags to be parsed. Besides, your taglib URI is far outdated. There has to be a `/jsp` in between. – BalusC Oct 09 '10 at 15:25