【学习笔记】JSTL 标签库

一、概念

JSTL 标签库 全称是指 JSP Standard Tag Library JSP 标准标签库。是一个不断完善的开放源代码的 JSP 标签库。
EL 表达式主要是为了替换 jsp 中的表达式脚本, 而标签库则是为了替换代码脚本。 这样使得整个 jsp 页面变得更佳简洁。
在这里插入图片描述
在 jsp 标签库中使用 taglib 指令引入标签库
格式
<%@ taglib prefix=“前缀” uri=“URL” %>

二、使用步骤

  1. 导入 jstl 标签库的 jar 包
    在这里插入图片描述
    注意:lib 文件放在 WEB-INF 下
    在这里插入图片描述

注意:lib 文件放在 WEB-INF 下
在这里插入图片描述

  1. 使用 taglib 指令引入标签库
    <%@ taglib prefix=“c” url=“http://java.sun.com/jsp/jstl/core” %>

三、核心库的使用

<c:set />

作用: set 标签可以往域中保存数据

    <body>
        ${sessionScope.key01}<%--保存之前--%>
        <c:set scope="session" var="key01" value="value"/>
        ${sessionScope.key01}<%--保存之前--%>
 	 </body>

<c:if />

if 标签用来做 if 判断。

    <body>
    <c:if test="${12==12}">
        <h1>12 = 12</h1>
    </c:if>
  </body>

<c:choose> <c:when> <c:otherwise>

作用: 多路判断。 跟 switch … case … default 非常接近。

    <body>
    <c:set scope="page" var="key" value="180"/>
    
    <c:choose>
        <c:when test="${pageScope.key<180}">
            <h1>小于180</h1>
        </c:when>
        <c:when test="${pageScope.key==180}">
            <h1>等于180</h1>
        </c:when>
        <c:when test="${pageScope.key>180}">
            <h1>大于180</h1>
        </c:when>
        <c:otherwise>
            <h1>啥也不是</h1>
        </c:otherwise>
    </c:choose>

  </body>

<c:forEach />

作用: 遍历输出使用。

遍历1~10

   <%--
        begin 属性设置开始的索引
        end 属性设置结束的索引
        var 属性表示循环的变量(也是当前正在遍历到的数据)
        step 属性表示遍历的步长值
    --%>
        <c:forEach begin="1" end="10" var="i">
            ${
    
    i}
        </c:forEach>

遍历Object 数组

    <body>
    <%--
        items 表示遍历的数据源(遍历的集合)
        var 表示当前遍历到的数据
    --%>
    <%
        pageContext.setAttribute("arr",new String[]{
    
    "123","456"});
    %>
    <c:forEach items="${pageScope.arr}" var="item">
        ${
    
    item}
    </c:forEach>
    </body>

遍历map

    <body>
    <%--
        items 表示遍历的数据源(遍历的集合)
        var 表示当前遍历到的数据
    --%>
    <%
        Map map = new HashMap();
        map.put("k1","v1");
        map.put("k2","v2");
        pageContext.setAttribute("map",map);
    %>
    <c:forEach items="${pageScope.map}" var="entry">
        ${
    
    entry.key} = ${
    
    entry.value}
    </c:forEach>

    </body>

猜你喜欢

转载自blog.csdn.net/DREAM_yao/article/details/114154297