看笔记之前,请确保你有一定的基础,推荐先看我博客的前几个关于JSP的笔记。自认为非常详细和易懂。
JSP Standard Tag Library JSP 标准标签库,JSP 为开发者提供的⼀系列的标签,使⽤这些标签可以完成 ⼀些逻辑处理,比如循环遍历集合,让代码更加简洁,不再出现 JSP 脚本穿插的情况。 实际开发中 EL 和 JSTL 结合起来使用,JSTL 侧重于逻辑处理,EL负责展示数据。
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
forEach遍历
我们写一个Servlet类,路径映射为jstl,里面设置一个集合。最后用JSTL中的forEach去遍历出来
public class User {
private String name;
private Integer age;
private String city;
public User(String name, Integer age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", city='" + city + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
@WebServlet("/jstl")
public class Jstl extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<User> list = new ArrayList<>();
list.add(new User("乐",18,"广东"));
list.add(new User("心",19,"广东"));
list.add(new User("湖",20,"广东"));
req.setAttribute("users",list);
req.getRequestDispatcher("jstl.jsp").forward(req,resp);
}
}
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<table>
<tr>
<th>名字</th>
<th>年龄</th>
<th>地方</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.name}</td>
<td>${user.age}</td>
<td>${user.city}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
set、out、remove、catch