|
|
|
How to loop arraylist |
Purpose of this tutorial is to show how to iterate/loop through an ArrayList of objects/dtos and access dto fields and display data.
This is most commonly needed where list is fetched from database and then it is displayed in a JSP.
Steps
1. Create data transfer object for testing.
2. Create jsp to use simple for loop in first scenario and then use JSTL tags in second
Also see
3. Create servlet to create ArrayList for testing
4. Add servlet to web.xml
5. Run
com.company.servlet.User.java
package com.company.servlet;
import java.io.Serializable;
public class User implements Serializable{
private String firstName;
private String lastName;
private String userId;
private String userRole;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
}
/jsp/iterator.jsp
<%@ page import="com.company.servlet.User" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<jsp:useBean id="cartoonUsers" class="java.util.ArrayList" scope="request"/>
<html>
<body>
<table bgcolor="#EFEFEF" border="1" >
<tr>
<td colspan="4"><Strong>1: Data displayed using for loop and <%=> tag</Strong></td>
</tr>
<tr>
<td><Strong>First Name</Strong></td>
<td><Strong>Last Name</Strong></td>
<td><Strong>User Id</Strong></td>
<td><Strong>User Role</Strong></td>
</tr>
<%
for(int i=0; i<cartoonUsers.size(); i++)
{
User user = (User)(cartoonUsers.get(i));
%>
<tr>
<td><%=user.getFirstName()%></td>
<td><%=user.getLastName()%></td>
<td><%=user.getUserId()%></td>
<td><%=user.getUserRole()%></td>
</tr>
<%
}
%>
</table>
<br/>
<br/>
<br/>
<table bgcolor="#EFEFEF" border="1" >
<tr>
<td colspan="4"><Strong>2: Data displayed using JSTL tags</Strong></td>
</tr>
<tr>
<td><Strong>First Name</Strong></td>
<td><Strong>Last Name</Strong></td>
<td><Strong>User Id</Strong></td>
<td><Strong>User Role</Strong></td>
</tr>
<c:forEach var="user" items="${cartoonUsers}" >
<tr>
<td>${user.firstName}</td>
<td>${user.lastName}</td>
<td>${user.userId}</td>
<td>${user.userRole}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
Following tags are used <jsp:useBean>, <c:forEach> in this JSP
com.company.servlet.IteratorServlet.java
package com.company.servlet;
import java.util.ArrayList;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class IteratorServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws javax.servlet.ServletException, java.io.IOException {
process(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws javax.servlet.ServletException, java.io.IOException {
process(request, response);
}
public void process(HttpServletRequest request, HttpServletResponse response)
throws javax.servlet.ServletException, java.io.IOException {
System.out.println("Inside IteratorServlet::process()");
//Let us create an ArrayList with multiple User objects for testing
User user1 = new User();
user1.setFirstName("Donald");
user1.setLastName("Duck");
user1.setUserId("ddonald");
user1.setUserRole("duck");
User user2 = new User();
user2.setFirstName("Micky");
user2.setLastName("Mouse");
user2.setUserId("mmouse");
user2.setUserRole("mouse");
User user3 = new User();
user3.setFirstName("Pluto");
user3.setLastName("Dog");
user3.setUserId("pdog");
user3.setUserRole("dog");
ArrayList<User> cartoonUsers = new ArrayList<User>();
cartoonUsers.add(user1);
cartoonUsers.add(user2);
cartoonUsers.add(user3);
request.setAttribute("cartoonUsers", cartoonUsers);
request.getRequestDispatcher
("/jsp/iterator.jsp").forward(request,
response);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>ServletApp</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<display-name>IteratorServlet</display-name>
<servlet-name>IteratorServlet</servlet-name>
<servlet-class>com.company.servlet.IteratorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>IteratorServlet</servlet-name>
<url-pattern>/IteratorServlet</url-pattern>
</servlet-mapping>
</web-app>
Now launch page
Please note that both these implementations are XSS vulnerable in their current form. You should avaoid using
<%=%> tag unless absolutly necessary. Use <c:out> tag with escapeXml="true" to display user entered data and protect applications from XSS attack.
Following section describes various errors you may encounter while using JSTL tags
org.apache.jasper.JasperException:
According to TLD or attribute directive in tag file, attribute items does not accept any expressions
Resolution : Check <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> line in your JSP. It should be
uri="http://java.sun.com/jsp/jstl/core" and not uri="http://java.sun.com/jstl/core"
org.apache.jasper.JasperException:
The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or
the jar files deployed with this application
Resolution : If you are running it in Tomcat check standard.jar and jstl.jar is either available in applications /WEB-INF/lib/ directory
or put it in TOMCAT classpath.
See next
|
|
|
| How to loop arraylist JAVA6 Syntax
|
| How to iterrate through ArrayList and display multiple rows using for loop JAVA6 syntax..
|
| Java JSP |
2010-Oct-12 |
| How to loop arraylist
|
| How to iterrate through ArrayList and display multiple rows using for loop, JSTL tags..
|
| Java JSP |
2010-Oct-12 |
| Consumer using JAX WS Dispatch API and DOM parser 1
|
| Access/Consume Webservice using Servlet, JAX-WS Dispatch API dynamic client and parsing SOAP response using DOM parser...
|
| Java Webservice |
2010-Sep-20 |
| Simple Java first CXF Webservice 4
|
| Building Simple Java first CXF webservice using CXFServlet, Spring, jaxws:endpoint, @WebService, @SOAPBinding, @WebResult
|
| Java Webservice |
2010-Sep-19 |
| Simple Java first CXF Webservice 3
|
| Building Simple Java first CXF webservice using CXFServlet, Spring, jaxws:endpoint, @WebService, @SOAPBinding, @WebResult
|
| Java Webservice |
2010-Sep-18 |
| Simple Java first CXF Webservice 1
|
| Building Simple Java first CXF webservice using CXFServlet, Spring, jaxws:endpoint, @WebService, @SOAPBinding, @WebResult
|
| Java Webservice |
2010-Sep-18 |
| Simple Java first CXF Webservice 2
|
| Building Simple Java first CXF webservice using CXFServlet, Spring, jaxws:endpoint, @WebService, @SOAPBinding, @WebResult
|
| Java Webservice |
2010-Sep-18 |
| Encoding special characters in userinput or on server
|
| Encoding can be done either in Javascript or JAVA encodeURIComponent, escape, java.net.URLEncoder..
|
| Java JSP |
2010-Aug-09 |
| Jstl fmt tag i18n formatdate formatcurrency
|
| fmt:setBundle, native2ascii.exe, fmt:message, fmt:setLocale, fmt:formatDate, fmt:formatNumber type=currency..
|
| Java JSP |
2010-Aug-05 |
| How to read and write a file
|
| How to read and write a file java.io.BufferedReader,java.io.FileReader, InputStreamReader ...
|
| Java J2SE |
2010-Aug-04 |
| jQuery validate form using ajax 2
|
| How to validate/submit form using ajax and jQuery input#, ($.ajax)..
|
| Javascript |
2010-Jul-23 |
| jQuery validate form using ajax 1
|
| How to validate/submit form using ajax and jQuery ($.ajax)..
|
| Javascript |
2010-Jul-23 |
| How to create datasource in RAD Websphere
|
| Create JDBC provider, datasource and JAAS security setup, JDBC connection URLs
|
| Servers Websphere |
2010-Jul-08 |
| Get Started 4
|
| Struts2 framework structure, how various components fit together
|
| Java Struts2 |
2010-Jul-07 |
| How to populate a form when JSP is called first time
|
| This is achieved throught setting bean in request, using frameworks like Struts2, Spring3..
|
| Java JSP |
2010-Jul-07 |
| Spring3 And Hibernate 4
|
| Spring3 and Hibernate 3.5.3 working together @Controller, @RequestMapping, @InitBinder, HibernateTransactionManager, LocalSessionFactoryBean, HibernateTemplate
|
| Java Spring |
2010-Jul-07 |
|
|