Iterating through a List in jsp (jsp:

2019-05-23 03:45发布

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条回答
走好不送
2楼-- · 2019-05-23 04:06

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()

查看更多
登录 后发表回答