1.JSTL介绍
- JSTL(Java Server Pages Standarded Tag Library) : JSP标准标签库。
- 主要提供给开发人员一个标准通用的标签库。
开发人员可以利用这些标签取代JSP页面上的Java 代码,从而提高程- 序的可读性,降低程序的维护难度
组成部分如下:
2.JSTL核心标签使用
<1>常见核心标签
<2>操作步骤
【第一步】导入jstl-1.2.jar包
【第二步】在jsp页面使用taglib指令引入核心标签库
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<3>代码实现
- if和choose标签
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
<%request.setAttribute("number",-100);
%>
<!--if标签:相当于Java的if语句-->
<c:if test="${number%2==0}">${number}是偶数
</c:if><!--choose标签:相当于Java的if...else if...else...语句-->
<c:choose><c:when test="${number>=0 && number<=20}"><h2>number在0到20之间</h2></c:when><c:when test="${number>20}"><h2>number大于20</h2></c:when><c:otherwise><h2>number小于0</h2></c:otherwise>
</c:choose>
</body>
</html>
浏览器展示:
- foreach标签
<!--foreach标签:相当于Java的for循环,前提:先向域对象中存储集合,名称叫list-->
<c:forEach var="i" begin="0" end="${list.size()}" step="1" >${list[i].name},${list[i].age}<br>
</c:forEach><!--foreach标签:类似Java增强for循环,前提:先向域对象中存储集合,名称叫list-->
<c:forEach var="user" items="${list}">${user.name},${user.age}<br>
</c:forEach>
练习:
学生封装代码:
<head><title>流程控制</title>
</head>
<style>table {text-align: center;}
</style>
<body>
<%Student student1=new Student("张三",20);Student student2=new Student("张益达",22);Student student3=new Student("张三",20);Student student4=new Student("张益达",22);Student student5=new Student("张三",20);ArrayList<Student> list=new ArrayList<>();list.add(student1);list.add(student2);list.add(student3);list.add(student4);list.add(student5);request.setAttribute("students",list);
%>
</body>
需求1:将学生信息遍历显示到table表格中。
需求2:奇数行数据背景色是pink粉色,偶数行数据背景色是gray灰色
【只写body里面的内容】
实现方式一:
<table align="center" border="1" width="40%" cellspacing="0"><tr><th>编号</th><th>姓名</th><th>年龄</th></tr>
<%-- step 每次运行完+1--%><c:forEach var="i" begin="0" end="${students.size()-1}" step="1"><c:if test="${(i+1)%2==1}"><tr align="center" style="background-color: gray"><td>${i+1}</td><td>${students.get(i).name}</td><td>${students.get(i).age}</td></tr></c:if><c:if test="${(i+1)%2==0}"><tr align="center" style="background-color: pink"><td>${i+1}</td><td>${students.get(i).name}</td><td>${students.get(i).age}</td></tr></c:if></c:forEach>
</table>
实现方式二:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<table align="center" border="1" width="40%" cellspacing="0"><tr><th>编号</th><th>姓名</th><th>年龄</th></tr><c:forEach items="${students}" var="stu" varStatus="statu"><c:if test="${statu.count%2==1}"><tr align="center" style="background-color: pink"><td>${statu.count}</td><td>${stu.name}</td><td>${stu.age}</td></tr></c:if><c:if test="${statu.count%2==0}"><tr align="center" style="background-color: gray"><td>${statu.count}</td><td>${stu.name}</td><td>${stu.age}</td></tr></c:if></c:forEach>
</table>
</html>
两种方法展示界面:
jstl-1.2资源下载