Jsp,JSTL中常用判断,循环语句对比
一,<c:out/>
<c:out value="aaa"></c:out> 输出aaa
<c:out value="${aaa}"></c:out> 与${aaa}相同
<c:out value="${aaa}" default="bbb"/> 当${aaa}不存在时候.输出bbb
<c:out value="${aaa}" default="bbb" escapeXml="false"/> 当escapeXml为false时候,不会转换'aaa'中的'<','>' 但是这样可能会受到js恶意输出,如:<%request.setAttribute("a","<script>alert('hello')</script>");%>
二,<c:set/>
<c:set var="aaa" value="hello"></c:set>在pageContext中添加key为aaa,value为hello的数据
<c:set var="aaa" value="hello" scope="session"></c:set>在session中添加key为aaa,value为hello的数据
三,<c:remove/>
<%
pageContext.setAttribute("aaa","hello1");
request.setAttribute("aaa","hello2");
session.setAttribute("aaa","hello3");
application.setAttribute("aaa","hello4");
%>
<c:remove var="aaa"></c:remove>
删除上面四个域中的所有key为'aaa'的数据
<c:remove var="aaa" scope="page"></c:remove> 删除pageContext中的key为'aaa'的数据
四,<c:if/>
if标签的test属性必须是一个boolean类型的值,如果test的值为true,那么执行if标签的内容,否则不执行。
<c:if test="${user.status == 0}">已启用</c:if>
<c:if test="${user.status != 0}">已停用</c:if>
五,<c:choose/>
choose标签对应Java中的if/else
if/else结构。when标签的test为true时,会执行这个when的内容。当所有when标签的test都为false时,才会执行otherwise标签的内容。
<c:choose>
<c:when test="${score > 100}">牛皮1的分数</c:when>
<c:when test="${score > 90}">牛皮2的分数</c:when>
<c:when test="${score > 80}">牛皮3的分数</c:when>
<c:when test="${score < 10}">你的分数</c:when>
<c:otherwise>没有分</c:otherwise>
</c:choose>
六,<c:foreach/>
forEach当前就是循环标签了,forEach标签有多种两种使用方式:
-使用循环变量,指定开始和结束值,类似for(int i=1;i<=10;i++){};
xx -循环遍历集合,类似for(Object o:集合);
Ⅰ,常用属性
<c:forEach items="${allBooks}" var="book" begin="" end="">
</c:forEach>
Ⅱ,遍历集合和数组,List同样如此
<%
String[] names = {"zhangsan","lisi","wanger","mazi","wangwu"};
pageContext.setAttribute("names",names);
%>
<c:forEach items="${names}" var="name">
<c:out value="name:${item}"/>
</c:forEach>
Ⅲ,遍历Map
<%
Map<String,String> names = new LinkedHashMap<String,String>();
names.put("1","zs");
names.put("2","wu");
names.put("3","sa");
names.put("4","ds");
pageContext.setAttribute("names",names);
%>
<c:forEach items="${names}" var="name">
<c:out value="${item.key}:${item.value}"/>
</c:forEach>