JSTL由五个不同功能的标签库组成
-
c:核心标签库(重点)
set
if
choose、when、otherwise
forEach -
fmt:格式化
-
fn:函数
-
sql:数据库(不使用)
-
x:XML(不使用)
导入jar包,然后在jsp页面导入jstl,一般都是软件会自动导入
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
set
作用:往域中保存数据
域对象:setAttribute(key,value)
scope 属性设置保存到哪个域
page——>PageContext域(默认)
request——>Request域
session——>Session域
opplication——>ServletContext域
var属性设置key
value属性设置value
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<script src="${ctx}/html/js/json.js"></script>
if
作用:作if判断(没有else)
test属性表示判断的条件(使用EL表达式输出)
<c:if test="${pageContext.request.localAddr=='0:0:0:0:0:0:0:1'}">
<c:set var="ip" value="localhost" />
</c:if>
choose、when、otherwise
作用:多路判断(switch…case…default)
注意:不能使用html注释,要使用jsp注释(<%--注释--%>
)
<%
request.setAttribute("height",180);
%>
<c:choose>
<c:when test="$(requestScope.height>190)"><h2>小巨人</h2></c:when>
<c:when test="$(requestScope.height>180)"><h2>很高</h2></c:when>
<c:when test="$(requestScope.height>170)"><h2>一般般</h2></c:when>
<otherwise>
<c:choose>
<c:when test="$(requestScope.height>160)"><h2>160</h2></c:when>
<c:when test="$(requestScope.height>150)"><h2>150</h2></c:when>
<otherwise>其他</otherwise>
</c:choose>
</otherwise>
</c:choose>
forEach
作用:遍历
begin:设置开始的索引
end:设置结束的索引2
var:循环的变量
items:设置循环的数组
step:遍历的步长值(i++)
遍历数值、Object、Map和List
<%
request.setAttribute("arr",new String[]{"123","456","789"})
%>
<%
Map<String,Object>map=new HashMap<String,Object>();
map.put("key1","value1");
map.put("key2","value2");
map.put("key3","value3");
map.put("key4","value4");
request.setAttribute("map",map)
%>
<c:forEach begin="1" end="10" var="i">
${i}
</c:forEach>
<c:forEach items="${requestScope.arr}" var="item">
${item}
</c:forEach>
<c:forEach begin="1" end="2" step="2" items="${requestScope.map}" var="entry">
${entry}
<%--或者--%>
${entry.key}=${entry.value}
</c:forEach>