EL、JSTL表达式的基本用法

EL、JSTL表达式的基本用法

EL表达式的基本使用:

格式: ${ 表达式 }

    <%
        // 往作用域中存储数据
        request.setAttribute("name", "request");

        String [] array = {"aa","bb","cc","dd"};
        application.setAttribute("strArr", array);

        Map map = new HashMap();
        map.put("key", "value");
        pageContext.setAttribute("map", map);

        Student stu = new Student("Mary", "28");
        session.setAttribute("student", stu);
    %>

    使用EL表达式取值:
    // 取字符串
    ${ requestScope.name }
    // 取数组
    ${ applicationScope.strArr[0] }, ${ pageScope.strArr[1] }
    // 取Map集合
    ${ pageScope.map.key }
    // 取普通对象
    ${ sessionScope.student.age }

总结:
如果取的数值是有下标例如Array、List,则使用[]的方式取值,如果取的数值是无下标例如Map、Student,直接使用.的方式取值

PS: 在取值的时候可以省略pageScope等前缀, 这时候会默认先从page开始找,遍历四个作用域寻找相应的数据,例如直接 ${map.key}

JSTL表达式的基本使用:

  • 导入jar包
  • 使用taglib引用标签库 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  • 使用标签 (标签库必须选用1.0以上版本,1.0不支持EL表达式)

    1. set 标签:

      <!-- 
      声明一个对象name, 对象的值 Mary , 存储到了session中 ,不指定scope默认page
      -->
      <c:set var="name" value="Mary" scope="session"></c:set>
      
    2. if 标签:

      <%
          int count = 20;
          session.setAttribute("num", count);
      %>
      
      <!-- 
      判断test里的条件是否满足,满足则执行<c:if>里的语句, c:if语句是没有else的
      -->
      <c:if test="${ sessionScope.num > 20 }">
          count > 20
      </c:if>
      <c:if test="${ sessionScope.num < 20 }">
          count <= 20
      </c:if>
      
      <!--定义一个名为flag的变量,用于接收test的判断结果,并存入request域中 -->
      <c:if test="${ sessionScope.num == 20 }" var="flag" scope="request">
          count 等于 20
      </c:if>
      
    3. forEach 标签:

      <!-- 遍历list对象,从下标0开始遍历到10,遍历的结果存储到obj中 -->
      <c:forEach item="${list}" begin="0" end="10" var="obj">
      
      </c:forEach>
      

猜你喜欢

转载自blog.csdn.net/JackJunL/article/details/81210173
今日推荐