23. JSTL

简介

JSTL,JSP Standard Tag Library,JSP 标准标签库

作用

替代 JSP 中的脚本代码(% 中代码)

使用

  1. 需要导入包。taglibs-standard-impl-1.2.5.jar 和 taglibs-standard-spec-1.2.5.jar
  2. 并引入标签库。<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

常用标签

  1. c:set
1
2
3
<!-- JSTL: -->
<!-- scope 的默认值为 page -->
<c:set value="100" var="i" scope="page"></c:set>
  1. c:out
1
2
3
<!-- 从指定 scope 中取值,写法依赖 EL,但是 JSTL 可以设置默认值和设置是否解析特殊字符 -->
request: <c:out value="${requestScope.i}" ></c:out>
page: <c:out value="${pageScope.i}" ></c:out>
  1. c:remove
1
2
3
4
<!-- 从指定 scope 中删除值,如果不指定 scope 则从所有域中删除 -->
<c:remove var="i" scope="request"/>
request:<c:out value="${requestScope.i}" ></c:out>
page:<c:out value="${pagetScope.i}" ></c:out>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

使用示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- JSP: -->
<%
int i=10;
request.setAttribute("i", i);
%>
<%=i %> <!-- 输出 10 -->

<!-- JSTL: -->
<!-- scope 的默认值为 page -->
<c:set value="100" var="i" scope="page"></c:set>

<!-- 从指定 scope 中取值,写法依赖 EL,但是 JSTL 可以设置默认值和设置是否解析特殊字符 -->
request: <c:out value="${requestScope.i}" ></c:out> <!-- 输出 request: 10 -->
page: <c:out value="${pageScope.i}" ></c:out> <!-- 输出 page: 100 -->

<!-- 从指定 scope 中删除值,如果不指定 scope 则从所有域中删除 -->
<c:remove var="i" scope="request"/>
request:<c:out value="${requestScope.i}" ></c:out> <!-- 输出 request: -->
page:<c:out value="${pageScope.i}" ></c:out> <!-- 输出 page:100 -->

</body>
</html>
  1. c:if
1
2
3
<c:if test="${empty i}">
"i" is null
</c:if>
  1. <c:choose>
1
2
3
4
5
6
7
8
<c:choose>
<c:when test="${ i < 10}">
i < 10
</c:when>
<c:otherwise>
i >= 10
</c:otherwise>
</c:choose>
  1. <c:forEach>
1
2
3
<c:forEach var="i" begin="1" end="100" step="2">
${i}
</c:forEach>
1
2
3
4
5
6
7
<%
String[] aa = new String[]{"1", "2", "3"};
request.setAttribute("aa", aa);
%>
<c:forEach items="${ aa }" var="aaa">
${ aaa }
</c:forEach>