三、JSTL 技术
1.JSTL 概述
JSTL (Jsp Standard Tag Library), Jsp 标准标签库,可以嵌入在 jsp 页面中使用标签的形式完成业务逻辑等功能。 JSTL 出现的目的和 EL 一样,也是要替代 jsp 页面中的脚本代码。 JSTL 标准标签库有 5 个字库,但随着发展,目前长使用的是它的核心库。
标签库 | 标签库的 URI | 前缀 |
Core | http://java.sun.com/jsp/jstl/core | c |
I18N | http://java.sun.com/jsp/jstl/tmt | fmt |
SQL | http://java.sun.com/jsp/jstl/sql | sql |
XML | http://java.sun.com/jsp/jstl/xml | xml |
Functions | http://java.sun.com/jsp/jstl/function | fn |
2.JSTL 下载与导入
JSTL 下载:
从 Apache 的网站下载 JSTL 的 JAR 包。进入“http://archive.apache.org/dist/jakarta/taglibs/standard/binaries/”网址下载 JSTL 的安装包。jakarta-taglibs-standard-1.1.2.zip,然后将下载好的 JSTL 的安装包
使用 taglib 指令导入标签库:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
3.JSTL 标签库的常用标签
1)<c:if test = ""> 标签
其中 test 是返回 boolean 的条件
<%
request.setAttribute("count", 10);
%>
<c:if test="${count==10}">
xxxx
</c:if>
<c:if test="${count!=10 }">
yyyy
</c:if>
效果:
2)<c:forEach> 标签
示例:
<!-- 第一种 -->
<c:forEach begin="1" end="5" var="i">
${i}<br/>
</c:forEach>
<!-- 第二种 -->
<!--
List<Product> productList
-->
<!-- item 表示一个数组或是集合 -->
<c:forEach items="${productList }" var="pro">
${pro.pName }
1)遍历 List<String>的值
<%
//模拟List<String> strList
List<String> strList = new ArrayList<String>();
strList.add("ma");
strList.add("yang");
strList.add("zhang");
strList.add("yu");
strList.add("zhao");
strList.add("zhou");
request.setAttribute("strList", strList);
%>
<h1>1、取出 strList 的数据 </h1>
<c:forEach items="${strList }" var="str">
${str }
</c:forEach>
效果:
2)遍历 List<User>的值
<%
//模拟List<User> userList
User user01 = new User();
user01.setId(1);
user01.setName("dongfangbubai");
user01.setPassword("123456");
User user02 = new User();
user02.setId(2);
user02.setName("ximenchuixu");
user02.setPassword("234561");
User user03 = new User();
user03.setId(3);
user03.setName("linghuchong");
user03.setPassword("345621");
List<User> userList = new ArrayList<User>();
userList.add(user01);
userList.add(user02);
userList.add(user03);
request.setAttribute("userList", userList);
%>
<h1>2、取出List<User>的值 </h1>
<c:forEach items="${userList }" var="user">
用户 ID:${user.id }
用户姓名:${user.name }
用户密码:${user.password }
</c:forEach>
效果:
3)遍历 Map<String,String>的值
<%
//遍历 Map<String,String> 的值
Map<String,String> strMap = new HashMap<String,String>();
strMap.put("name", "Tom");
strMap.put("age", "18");
strMap.put("addr", "NewYork");
session.setAttribute("strMap", strMap);
%>
<h1>3、取出 strMap 中的数据</h1>
<c:forEach items="${strMap }" var="entry">
${entry.key }:${entry.value }
</c:forEach>
效果:
4)遍历 Map<String,User>的值
<%
//遍历Map<String,Map>的值
Map<String,User> userMap = new HashMap<String,User>();
userMap.put("user01", user01);
userMap.put("user02", user02);
userMap.put("user03", user03);
%>
<h1>4、取出 userMap 中的数据</h1>
<c:forEach items="${userMap }" var="entry">
${entry.key }:${entry.value .id}//
${entry.value .name}//
${entry.value .password}
</c:forEach>