Iterating through a List<CustomClass> in jsp (jsp:getProperty?)

主宰稳场 提交于 2020-01-13 21:26:32

问题


I want to iterate through a List that is a member variable of a User object. I don't want to use snippets and would like to use some form of jsp tags to do the trick.

User class

public class User {

  private List<Option> options;

  public getOptions()...
}

What I'm trying to do in snippets

<%
User user = (User)session.getAttribute("user");
List<Option> options = user.getOptions();
%>

<select id="alertFilter">

<% for (Option o : options) { %>

<option><%=o.getTitle()%></option>

<% } %>

</select>

I've seen a few simple examples of what I'm trying to do but they always get simple ojects back.

Tag Library way - not working

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<jsp:useBean id="user" class="ie.openmobile.smsjobs.entity.User" scope="request"></jsp:useBean>

<c:forEach var="options" items="$user.options" >   <--incorrect references to alerts/getOptions()

<br>$options.title   <--incorrect syntax

</c:forEach>

Can anyone help me out?


回答1:


Change it to as follows

<select id="alertFilter">

<c:forEach var="option" items="${user.options}" >
  <option><c:out value="${option.title}"/></option>
</c:forEach>

</select>

Explanation : ${user.options} will get the user from session and options collection using its getOptions() method, and it will iterate on each entry

While under the iteration ${option.title} would give the option ( which is the current option instance under traversal) and option.getTile()



来源:https://stackoverflow.com/questions/11342440/iterating-through-a-listcustomclass-in-jsp-jspgetproperty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!