JSTL使用
1.什么是JSTL
JSTL是Jsp Standard Tag Library的缩写,jsp标准标签库,用来替代jsp中的代码脚本,是其更为简洁、规范。
2.JSTL使用步骤
在使用JSTL时要导入相关的jar包,taglibs-standard-impl-1.2.1.jar和taglibs-standard-spec-1.2.1.jar两个jar包,然后使用taglib指令在jsp页面中引入标签库。
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
3.core库中各种标签的使用
①<c:set />标签
作用:用来设置域对象中的值,代码示例:
<c:set scope="request" var="var1" value="value1"/><br>
${ requestScope.var }
其中scope属性用来指明设置的域对象,var用来设置变量的变量名,value用来设置变量值。
②<c:if />标签
作用:用来进行判断,但是不能进行多路判断,代码示例:
<%-- 使用<c:if />标签用来判断--%>
<c:if test="${ 13 > 12 }" >
13大于12
</c:if>
③<c:choose /><c:where /><c:otherwise />标签
作用:可以用来进行判断,支持多路判断,代码示例:
<%-- 使用<c:choose />\<c:where /><c:otherwise />来判断--%>
<c:set scope="request" var="height" value="161" />
<c:choose>
<c:when test="${ requestScope.height > 170}">
<h3>高于170</h3>
</c:when>
<c:when test="${ requestScope.height > 160 and requestScope.height < 170}">
<h3>高于160矮于170</h3>
</c:when>
<c:otherwise>
<h3>矮于160</h3>
</c:otherwise>
</c:choose>
注意:1.在<:c:choose>:中不要使用html;2.在<:c:when>:必须在<:c:choose>:中使用。
④<c:forEach />
作用:可以用来进行循环操作,代码示例:
<%-- 使用<c:forEach />来进行循环操作 --%>
<%-- 输出1到10--%>
<c:forEach begin="1" end="10" var="i">
${ i }
</c:forEach><br>
<%-- 遍历Object对象数组 --%>
<%
String[] arr = new String[]{"111","222","333"};
request.setAttribute("arr", arr);
%>
<c:forEach items="${ arr }" var="item">
${ item }
</c:forEach><br>
<%-- 控制输出的开始或结束 --%>
<c:forEach items="${ arr }" var="item" begin="1">
${ item }
</c:forEach><br>
<c:forEach items="${ arr }" var="item" end="1">
${ item }
</c:forEach><br>
<c:forEach items="${ arr }" var="item" begin="1" end="1">
${ item }
</c:forEach><br>
<%-- 遍历Map集合 --%>
<%
HashMap<String, String> map = new HashMap<>();
map.put("key1","value1");
map.put("key2","value2");
map.put("key3","value3");
map.put("key4","value4");
request.setAttribute("map", map);
%>
<c:forEach items="${ map }" var="item">
${ item }<br>
</c:forEach>
<%-- 遍历List<Student>集合 --%>
<%
ArrayList<Student> list = new ArrayList<>();
for(int i = 1; i<10 ; i++ ){
list.add(new Student(i, "name"+1,"passowrd"+1, 18+i,"110"+i));
}
request.setAttribute("list",list);
%>
<c:forEach items="${ list }" var="item">
${ item }
${ item.phone }<br>
</c:forEach>
其中的begin和end属性用来设置遍历的其实和结束位置,其值对应数组中的索引,0表示第一个,items属性表示数据源即要遍历的数组或集合,var属性可以用来表示循环变量。