0

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
  • 2
    If you know how to do in java , you should already know about how to do in JSP. Commented Aug 7, 2012 at 10:23

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

can we create the list in hello.jsp itself?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.