JSTL
a.使用步骤(核心标签库)
第一步:导入jar包(jstl-xxx包,standard.jar)
第二步:在jsp页面引入标签库
<%@ taglib uri="http://java.sun.com/jsp/jst1/core" prefix="c"%>
第三步:使用<c:标签名/>
b.核心标签库标签
通用标签:set、out、remove
条件标签:if、choose
迭代标签:forEach
c. set标签
<c:set va”变量名” value=”值” scope=”作用范围”/>
<c:set traget=”对象名” property=”属性名” value=”值”/>
d. out标签
<c:out value=”${变量名}” default=”默认值” escapeXml=”Y”/>
e.removel标签
<c:rmovel var=”变量名”/>
f. if标签
<c:if test=”判断条件” var=”存储判断结果变量” scope=”作用范围”>
</c:if>
g. choose标签(类似java中if...else if...else)
<c:choose>
<c:when test=”判断条件”></c:when>
...
<c:otherwise></c:otherwise>
</c:choose>
h:forEach标签
<c:forEach items=”${集合变量}” var=”迭代当前对象变量”
Begin=”开始下标” end=”结束下标” step=”进步值”
statusValue=”当前对象的信息”/>
</c:forEach>
运行结果:
1 <%@page import="com.entity.Users"%> 2 <%@page import="org.apache.catalina.User"%> 3 <%@page import="java.util.Map"%> 4 <%@page import="java.util.HashMap"%> 5 <%@page import="java.util.ArrayList"%> 6 <%@page import="java.util.List"%> 7 <%@ page language="java" contentType="text/html; charset=UTF-8" 8 pageEncoding="UTF-8"%> 9 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 10 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 11 <html> 12 <head> 13 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 14 <title>Insert title here</title> 15 </head> 16 <body> 17 <%-- <c:set var="index" value="8" scope="request"></c:set> --%> 18 <%-- ${index} --%> 19 <%-- <c:remove var="index"/> --%> 20 <%-- ${index} --%> 21 <c:set var="index" value="8" scope="request"></c:set> 22 <c:remove var="index"/> 23 <c:if test="${empty index}" var="name" scope="request"> 24 没有值 25 </c:if> 26 <c:if test="${not empty index}"> 27 ${index} 28 </c:if> 29 <br/> 30 ${name} 31 <br/> 32 33 <!-- 1打印A、2打印B、否则打印C --> 34 <c:set var="index" value="2" scope="request"></c:set> 35 <c:choose> 36 <c:when test="${index==1}"> 37 A 38 </c:when> 39 <c:when test="${index==2}"> 40 B 41 </c:when> 42 <c:otherwise> 43 C 44 </c:otherwise> 45 </c:choose> 46 <br/> 47 48 <% 49 Users u1 = new Users(); 50 u1.setId(1); 51 u1.setName("zs1"); 52 Users u2 = new Users(); 53 u2.setId(2); 54 u2.setName("zs2"); 55 Users u3 = new Users(); 56 u3.setId(3); 57 u3.setName("zs3"); 58 List<Users> us = new ArrayList<Users>(); 59 us.add(u1); 60 us.add(u2); 61 us.add(u3); 62 request.setAttribute("us",us); 63 %> 64 <c:forEach items="${us}" var="uu"> 65 ${uu.id} ${uu.name}<br/> 66 </c:forEach> 67 <c:forEach begin="0" end="10" step="2"> 68 ${"*"} 69 </c:forEach> 70 <br/> 71 <% 72 Map<String,String> map = new HashMap<String,String>(); 73 map.put("a","A"); 74 map.put("b","B"); 75 map.put("c","C"); 76 request.setAttribute("map",map); 77 %> 78 <c:forEach items="${map}" var="en"> 79 ${en.key} 80 ${en.value}<br/> 81 </c:forEach> 82 </body> 83 </html>