简体   繁体   中英

For each loop with Expression Language

I want to print out every Item of my list "sorts" with Expression Language in a JSP File like that:

Try: Pizza-Margherita
Try: Cheese-Pizza

So it works if i use a normal expression like this

Try: ${sorts[0]}
Try: ${sorts[1]}

But i have to write it for every Item in the List

So I tried to use following two Loops:

<c:forEach items="${sorts}" var="item">
   Try: ${item}<br>
</c:forEach>


<c:forEach var="item" items="${sorts}">
    <td>
       Try: <c:out value="${item}" />
    </td>
</c:forEach>

It didn't work and I got this output each time:

Try:

Why won't my foreach loop work? what have I done wrong?

It is because you haven't included the core tag library in your JSP file. You will do this by inserting following Line at the top of your file.

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

Here is sample JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
   </head>
   <body>
      <c:forEach var="item" items="${sorts}">
         ${item.name}
      </c:forEach>
   </body>
</html>

Here is Sample Java Code

List<Sort> sortList = new ArrayList<>();

Sort s1 = new Sort();
s1.setName("Pizza-Margherita");
Sort s2 = new Sort();
s2.setName("Cheese-Pizza");

sortList.add(s1);
sortList.add(s2);

request.setAttribute("sorts", sortList);

Sample Object class

public class Sort {
    private String name;
   //create getter and setter for name
}

Make sure you have imported JSTL Library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM