JSTL核心标签库简介
JSTL核心标签库常用的标签
每次遇到JSTL核心的几个标签我都需要百度,今天花点时间整理一下这些标签。
JSTL准备
需要导入相关的jar包。
- taglibs-standard-spec-1.2.5.jar
- taglibs-standard-impl-1.2.5.jar
- taglibs-standard-jstlel-1.2.5.jar
- xalan-2.7.1.jar
- serializer-2.7.1.jar
下载地址:
JSTL:http://pan.baidu.com/s/1dESNmDj
xalan:https://pan.baidu.com/s/1T4KHIv0yiy0p6meU8e3kfw
然后再在页面中通过 taglib 指令将标签库导入
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
c:if标签
用来判断
<c:if test="${user == 'root' }" var="v" scope="request">
欢迎登陆
</c:if>
- test:判断的条件。若为 true,则执行标签体中的内容,否则不执行。
- var:存储 test 的判断结果。
- scope:存储 test 判断结果的变量的存放范围。
c:choose标签
类似于 switch-case 语句。
<c:choose>
<c:when test="${num == '1'}">
我输入的是1
</c:when>
<c:when test="${num == '2'}">
我输入的是2
</c:when>
<c:when test="${num == '3'}">
我输入的是3
</c:when>
<c:otherwise>
我没输入
</c:otherwise>
</c:choose>
c:forEach标签
该标签用于循环遍历数组、集合(List、Set、Map)
- 遍历数组:
<%
Object[] food = {"烤鸡","冰淇淋","薯条","巧克力"};
request.getSession().setAttribute("food", food);
%>
<c:forEach items="${food}" var="f">
${f }
<br>
</c:forEach>
- 遍历List
<%
List<String> food = new ArrayList<>();
food.add("烤鸡");
food.add("冰淇淋");
food.add("薯条");
food.add("巧克力");
request.getSession().setAttribute("food", food);
%>
<c:forEach items="${food}" var="f">
${f }
<br>
</c:forEach>
- 遍历set
<%
Set<String> num = new HashSet<>();
program.add("1");
program.add("2");
program.add("3");
program.add("4");
request.getSession().setAttribute("num", num);
%>
<c:forEach items="${num }" var="n">
${n }
<br>
</c:forEach>
- 遍历map
<%
Map<String,String> map = new HashMap<>();
map.put("1", "num1");
map.put("2", "num2");
map.put("3", "num3");
pageContext.setAttribute("map", map);
%>
<c:forEach items="${map }" var="m">
${m.key } : ${m.value }
<br>
</c:forEach>
- 指定遍历的起始索引及步长
对于数组及 List,可以指定遍历的起始索引及步长。
<%
Object[] country = {"0中国","1美国","2德国","3法国","4英国","5瑞士","6瑞典","7意大利"};
pageContext.setAttribute("country", country);
%>
<c:forEach items="${country }" var="c" begin="1" end="4">
${c }
<br>
</c:forEach>
- begin:指定遍历开始索引,从 0 开始计数。
- end:指定遍历结束索引,遍历结果包含这个索引。