I’m having trouble getting the right number of elements in the ArrayList alt in the JSP page below. When I view the JSP it shows the size is 1 (<%=alt.size()%>) when it should be 3; I think I’m adding that method to the array in the generator class, so I don’t understand why it’s showing 1.
This is my jsp page:
<% ArrayList<Alert> a = AlertGenerator.getAlert(); pageContext.setAttribute('alt', a); %> <c:forEach var='alert' items='${alt}' varStatus='status' > <p>You have <%=alt.size()%> Active Alert(s)</p> <ul> <li><a href='#' class='linkthree'>${alert.alert1}</a></li> <li><a href='#' class='linkthree'>${alert.alert2}</a></li> <li><a href='#' class='linkthree'>${alert.alert3}</a></li> </ul> </c:forEach>
This is class that generates the alerts:
package com.cg.mock; import java.util.ArrayList; public class AlertGenerator { public static ArrayList<Alert> getAlert() { ArrayList<Alert> alt = new ArrayList<Alert>(); alt.add(new Alert('alert1','alert2','alert3')); return alt; } }
This is my bean class:
package com.cg.mock; public class Alert { String alert1; String alert2; String alert3; public Alert(String alert1, String alert2,String alert3) { super(); this.alert1 = alert1; this.alert2 = alert2; this.alert3 = alert3; } public String getAlert1() { return alert1; } public void setAlert1(String alert1) { this.alert1 = alert1; } public String getAlert2() { return alert2; } public void setAlert2(String alert2) { this.alert2 = alert2; } public String getAlert3() { return alert3; } public void setAlert3(String alert3) { this.alert3 = alert3; } }
To get 3 Alerts you can redesign as follows. Notice that there is only one property of the alert class. You can create a new instance of the Alert for each alert.
In the AlertGenerator:
And on the JSP:
Notice the ul’s are outside the forEach loop.