For each loop with Expression Language

随声附和 提交于 2019-12-26 01:06:12

问题


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?


回答1:


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" %>



回答2:


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.



来源:https://stackoverflow.com/questions/46663384/for-each-loop-with-expression-language

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