JSTL详解(四)

JSTL详解(四)

迭代标签的使用

 

如果使用scriptlets,那么,我们经常使用Iterator或者Enumeration来进行迭代,如:

       Iterator it = collection.iterator();

       while(it.hasNext()){

              SomeBean someBean = (SomeBean)it.next();

              out.println(someBean.getXXX());

              …………..

}

在前面的一次中,我们开发过一个迭代标签,JSTL中也提供了对迭代进行支持的标签,并且,他的功能比上一章的强大的多。JSTL中的迭代标签有两个:

l         <c:forEach>;

l         <c:forTokens>;

1、<c:forTokens>专门处理TokenString的迭代,可以指定一个或者是多个分隔符。由于他们使用的很少,在这里就不介绍了。

2、<c:forEach>是最常用的,他几乎能够完成所有的迭代任务,就象jsp中的for(int i=j;i<k;i++)下面我来详细介绍。(注意,“[]”里面的是可选条件)

语法:a、在Collection中迭代:

       <c:forEach [var=”varName”] items=”collection”  [varStatus=”varStatusName”]

       [begin=”begin”] [end=”end”] [step=”step”]>

       Body 内容

       </c:forEach>

      b、迭代固定的次数:

       <c:forEach [var=”varName”] [varStatus=”varStatusName”]

       begin=”begin” end=”end” [step=”step”]>

       Body 内容

       </c:forEach>

举例:c_forEach1.jsp(在Collection中迭代)

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

<%@ page contentType="text/html; charset=gb2312" language="java" %>

<%@ page import="java.util.*,com.j2ee14.ch12.User"%>

<%

   Collection users_c=new ArrayList();

 

   for(int i=0;i<3;i++) {

      User user=new User();

      user.setUserName("foo"+i);

      user.setPassword("foo"+i);      

      users_c.add(user);

   }

   session.setAttribute("users",users_c);

%>

 

<html>

<head>

  <title>JSTL:c:forEach的使用之一</title>

</head>

<body bgcolor="#FFFFFF"><center>

<h4>迭代某个collection中的元素。</h4>

 

<table border=1>

<tr><td>用户名</td><td>密码</td></tr>

<c:forEach var="users" items="${users}">

  <tr>

  <td><c:out value="${users.userName}"/></td>

  <td><c:out value="${users.password}"/></td>

  </tr>

</c:forEach>

   </table>  

</center></body>

</html>

 

举例:c_forEach2.jsp(迭代固定的次数)

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

<%@ page contentType="text/html; charset=gb2312" language="java" %>

<html>

<head>

  <tcounttle>JSTL:c:forEach的使用之二</tcounttle>

</head>

<body bgcolor="#FFFFFF"><center>

<h4>第二种迭代:50-60</h4>

 <c:forEach var="count" begin="50" end="60">

  <c:out value="${count}"/> **

</c:forEach>

<h4>第二种迭代:10 to 100,step=10</h4>

<c:forEach var="count" begin="10" end="100" step="10">

  <c:out value="${count}"/>**

</c:forEach>

</center>

</body>

</html>

 

原文地址:https://www.cnblogs.com/bbsno1/p/3257971.html