1.JSTL概述
JSP标准标签库(JSP Standard Tag Library)是java EE网络应用程序开发平台的组成部分,它在JSP规范的基础上,扩充了一个JSP的标签库来完成一些通用任务,必须XML数据处理,条件执行,数据访问,循环和国际化
使用时需要导包
jstl-impl.jar
在jsp页面中我们可以使用JSTL表示完成数据的判断,分支结构,循环
在使用JSTL表达式之前,需要在JSP页面中加入:
<% taglib url ="http://java.sun.com/jsp/jstl/core" prefix = "c"%>
2.JSTL使用
2.1 c:if
<%@ page import="com.q.Student" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %><%--
Created by IntelliJ IDEA.
User: 刘朝阳
Date: 2020/5/23
Time: 15:57
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--条件判断--%>
<%--
c:if判断标签中 test属性是必须的,不可缺省
test属性中的值是支持EL表达式的
--%>
<c:if test="${10>5}">
<h3>条件成立</h3>
</c:if>
<%
Student stu = new Student(1, "小刘", 16);
pageContext.setAttribute("stu",stu,PageContext.REQUEST_SCOPE);
List<Student> list = new ArrayList<>();
list.add(new Student(1,"小王",9));
list.add(new Student(2,"小王",9));
list.add(new Student(3,"小王",9));
pageContext.setAttribute("list",list,PageContext.REQUEST_SCOPE);
%>
<c:if test="${stu.age >10}">
<h1>我还是曾经那个少年</h1>
</c:if>
<c:if test="${stu.age <10}">
<h1>我还是曾经那个骚年</h1>
</c:if>
<hr>
<c:if test="${list[0].age == 9}">
<h1>年龄是九岁呀</h1>
</c:if>
<c:if test="${list[0].age != 9}">
<h1>您的年龄不是九岁</h1>
</c:if>
</body>
</html>
2.2 c: choose
<%--
Created by IntelliJ IDEA.
User: 刘朝阳
Date: 2020/5/23
Time: 16:16
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
int score=100;
request.setAttribute("score",score);
%>
<c:choose>
<c:when test="${score>=90}">
<h1>优秀</h1>
</c:when>
<c:when test="${score>=80}">
<h1>良</h1>
</c:when>
<c:when test="${score>=70}">
<h1>凑活</h1>
</c:when>
<c:when test="${score>=60}">
<h1>加油</h1>
</c:when>
</c:choose>
</body>
</html>
2.3 c:foreach
<%--
Created by IntelliJ IDEA.
User: 刘朝阳
Date: 2020/5/23
Time: 16:21
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--
c:foreach属性
var:临时变量,循环结构中可以 临时使用
begin:从何时开始,这里可以使用EL表达式
end:到何时结束,这里也可以使用EL表达式
step:间隔,默认为1
--%>
<c:forEach var="num" begin="0" end="10" step="1">
<h3>${num}
</h3>
</c:forEach>
<hr>
<table width="400px" align="center" border="1px">
<tr>
<th>ID</th>
<th>Name</th>
<th>age</th>
</tr>
<%--item表示需要便利的元素--%>
<c:forEach var="stu" items="${list}" begin="0" end="${list.size()} " >
<tr>
<td>${stu.id}</td>
<td>${stu.name}</td>
<td>${stu.age}</td>
</tr>
</c:forEach>
</table>
</body>
</html>