JSTL标签库
1.介绍
JSTL java standard tag lib : Java的标准标签库
tagLib 技术的出现,就是为了解决 JSP页面中大量的难于维护的 Java 代码。
2.下载引用
下载地址:
链接:https://pan.baidu.com/s/1Hk1CME_0sN4-3y89J6bRdw
提取码:3o7p
也可以在菜鸟教程上进行下载:https://www.runoob.com/jsp/jsp-jstl.html
下载完成后将引入lib目录下的两个jar包到我们的项目中
引入后在jsp文件中写入标签:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
这里传入的c其实是一个变量名称,后面标签前面都要携带作为标识,也可以更换其他的字符,但一般默认就是c
3.核心标签库方法
3.1<c:if>
标签使用:
格式:
<c:if test="<boolean>" var="<string>" scope="<string>">
...
</c:if>
- test为判断条件
- var为要存储的变量名
- scop为要存储的域对象
实际代码:
<c:if test="${!(1==3)}">
$END$
</c:if>
这里需要注意的是判定条件需要使用EL表达式包裹,否则无效
c:if后面是没有c:else标签写法的。
3.2 <c:choose>标签使用
<c:choose>
标签类似java中的switch语句,配合<c:when> <c:otherwise>
标签使用
格式:
<c:choose>
<c:when test="<boolean>">
...
</c:when>
<c:when test="<boolean>">
...
</c:when>
...
...
<c:otherwise>
...
</c:otherwise>
</c:choose>
实际案例:
<c:choose>
<c:when test="${1==1}">
格式正确
</c:when>
<c:otherwise>
格式错误
</c:otherwise>
</c:choose>
test中传入的只能是boolean类型,这点和switch不太一样
3.3 <c:forEach>标签使用
循环迭代
格式:
<c:forEach
items="<object>"
begin="<int>"
end="<int>"
step="<int>"
var="<string>"
varStatus="<string>">
...
</c:forEach>
- items是要迭代的对象
- begin 起始迭代的下标
- end 终止迭代的下标
- step 步长
- var 表示用一个变量来表示每个迭代对象
- varStautus传入一个变量可以表示迭代对象的索引位置
<%
request.setAttribute("examp",Arrays.asList("a","b","c","d","e","f"));
%>
<select>
<c:forEach
items="${examp}"
var="item">
<option>${item}</option>
</c:forEach>
</select>
显示结果:
集合中存放类并获取:
这里需要注意的是类的修饰需要添加public,否则在输出时访问拿不到
<%@ page import="java.util.Arrays" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %><%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/8/8
Time: 9:12
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<%!
public class Student{
private int age;
private String name;
private int sex;
public Student() {
}
public Student(int age, String name, int sex) {
this.age = age;
this.name = name;
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
}
%>
<%
List<Student> list = new ArrayList<>();
list.add(new Student(20,"wangwu",1));
list.add(new Student(10,"zhangsan",1));
list.add(new Student(30,"lisi",0));
request.setAttribute("list",list);
%>
<ul>
<c:forEach
items="${list}"
var="item"
varStatus="vs"
>
<li>${vs.count}${item.name}</li>
</c:forEach>
</ul>
</body>
</html>
实现结果: