JSTL

JSP Standard Tag Library JSP 标准标签库,JSP 为开发者提供的⼀系列的标签,使⽤这些标签可以完成
⼀些逻辑处理,比如循环遍历集合,让代码更加简洁,不再出现 JSP 脚本穿插的情况。
实际开发中 EL 和 JSTL 结合起来使用,JSTL 侧重于逻辑处理,EL负责展示数据。

使用

1、需要导⼊ jar 包(两个 jstl.jar standard.jar)存放的位置 web/WEB-INF/lib,下载地址:http://mirrors.hust.edu.cn/apache/

2、在 JSP 页面最上面引入 JSTL 标签库

  <%@ 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


Last modification:November 29, 2021
如果觉得我的文章对你有用,请随意赞赏