JSTL
概念:javaServer page Tag library jsp标准标签库
是由Apache组织提供的开源的免费的jsp标签
作用:用于简化和替换jsp页面上的java代码
使用步骤:
1.导入jstl相关的jar包
2.引入标签库:taglib指令 <%@taglib %>
3.使用标签
3.foreach :相当于java代码的for循环语句
foreach:相当于java代码的for语句
1:完成重复的操作
for(int i=0;i<10;i++){
}
属性:
begin :开始值(包含开始值) 相当于 i= 0
end :结束值(包含结束值) 相当于 i<10
var : 临时变量 相当于for语句中的 i
step : 步长 相当于for中 i++
varStatus:循环状态在容器中使用的多
index :容器中元素的索引 从0开始
count : 循环次数,从1开始
**2:遍历容器**
List<user> list
for(User user : list){
}
**属性:**
items : 容器对象
var :容器中元素的临时变量
varStatus : 循环状态对象
index :容器中元素的索引,从0开始
count : 循环此数,从1开始
项目准备:
一:导入jar包使用的是maven管理
<!--javaEE-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--jstl依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
二:前端页面展示代码:
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %><%--
Created by IntelliJ IDEA.
User: Lenovo
Date: 2020/3/6
Time: 21:14
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>foreach遍历集合元素的案例</title>
</head>
<body>
<%
List list = new ArrayList();
list.add("admin");
list.add("root");
list.add(222);
list.add(333);
request.setAttribute("list", list);
%>
<h2>使用foreach遍历重复的操作</h2>
<c:forEach begin="1" end="10" var="i" varStatus="s" step="2">
${s.index}<h1/> ${s.count}<h2/> ${i}<h4/>
</c:forEach>
<h1>使用foreach遍历容器list元素</h1>
<c:forEach items="${list}" var="it" varStatus="s">
${s.index} ${s.count} ${it}<br>
</c:forEach>
</body>
</html>
演示效果如图: