其他分享
首页 > 其他分享> > JSTL_概念和JSTL_常用标签、案例练习

JSTL_概念和JSTL_常用标签、案例练习

作者:互联网

JSTL_概念

概念:JavaServer Pages Tag Library JSP标准标签库

作用:用于简化和替换jsp页面上的java代码

使用步骤

  1. 导入jstl相关jar包
  2. 引入标签库:taglib指令:<%taglib%>
  3. 使用标签

JSTL_常用标签

JSTL标签_if

功能:和java中的if的功能是一样的

属性:

注意:c:if标签没有else情况 想要else情况 则可以在定义一共c:if标签

jsp代码

<%@ page import="java.util.ArrayList" %><%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/8/16
  Time: 17:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>if标签</title>
</head>
<body>

    <c:if test="true">
        <h1>我是真的...</h1>
    </c:if>
    <br>

    <%
        //判断request域中的一个list集合是否为空 如果不为null则显示遍历集合
        ArrayList list = new ArrayList();
        list.add("aaaa");
        request.setAttribute("list",list);

        request.setAttribute("number",3);
    %>

    <c:if test="${not empty list}">
        遍历集合...
    </c:if>
    <br>

    <c:if test="${number %2 !=0}">
        ${number}为奇数
    </c:if>
    <c:if test="${number %2 ==0}">
        ${number}为偶数
    </c:if>
</body>
</html>

运行结果

 

JSTL标签_Choose

功能:相当于java中的switch

jsp代码

<%@ 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>
    <% request.setAttribute("number",3); %>

<c:choose>
    <c:when test="${number == 1}">星期一</c:when>
    <c:when test="${number == 2}">星期二</c:when>
    <c:when test="${number == 3}">星期三</c:when>
    <c:when test="${number == 4}">星期四</c:when>
    <c:when test="${number == 5}">星期五</c:when>
    <c:when test="${number == 6}">星期六</c:when>
    <c:when test="${number == 7}">星期七</c:when>
    <c:otherwise>数字输出错误</c:otherwise>
</c:choose>

</body>
</html>

运行结果

JSTL标签_foreach

功能:相当于java中的for

for(int i=0;i<10;i++){

}
List<User> list;
for(User user : list){

}

jsp代码

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    ArrayList<Object> arr = new ArrayList<>();
    arr.add(0,"张三");
    arr.add(1,"李四");
    arr.add(2,"王五");
    arr.add(3,"赵六");
    arr.add(4,"田七");
    request.setAttribute("list",arr);
%>

<c:forEach var="arr" items="${list}">
    <c:out value="${arr}"/><br>
</c:forEach>

<hr>

<c:forEach var="arrr" items="${list}" begin="1" end="4"  step="2">
    <c:out value="${arrr}"/><br>
</c:forEach>

<hr>

<c:forEach var="arrr" items="${list}" begin="0" end="3"  step="1">
    <c:out value="${arrr}"/><br>
</c:forEach>

</body>
</html>

运行结果

标签:arr,java,标签,练习,JSTL,add,jsp
来源: https://www.cnblogs.com/aimz01/p/16592420.html