I want to create an arraylist of objects in JSP. And after that, want to loop through the list objects. can some one please help me in creating it.
1 Answer
Create the ArrayList at servlet set it as attribute, and iterate it on JSP using <c:forEach>
Servlet
List<Foo> list = new ArrayList<Foo>();
list.add(foo1);
list.add(foo2);
list.add(foo3);
request.setAttaribute("fooList", list);
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
hello.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:forEach items="${list}" var="foo">
<tr>
<td><c:out value="${foo.name}" /></td>
<td><c:out value="${foo.age}" /></td>
</tr>
</c:forEach>
Note: name and age are two properties of Foo with proper accessor methods
2 Comments
user1581636
can we create the list in hello.jsp itself?
toniedzwiedz
@user1581636 there is a way you can embed Java code directly in your JSP. It's called scriptlets. Just create a tag like this
<% /*Java code goes here*/ %> and you're done. However, using this technique is strongly discouraged. Scriptlets have been virtually replaced by the JSP Expression Language since JSTL 1.0. Also, mixing business and presentation logic makes your code unreadable.