還在使用JSP腳本嗎?快來學學EL 和JSTL 吧

JSP EL JSTL表達式

一、什麼是EL表達式

表達式語言(Expression Language,EL),EL表達式是用"${}"括起來的腳本,用來更方便的讀取對象!

  • EL表達式主要用來讀取數據,進行內容的顯示!

1、爲什麼要使用EL表達式?

EL語法很簡單,最大的特點就是使用上很方便

使用EL表達式可以方便地讀取對象中的屬性、提交的參數、JavaBean、甚至集合

EL表達式如果找不到相應的對象屬性,返回的的空白字符串“”,而不是null,這是EL表達式最大的特點!

1、結構與用法

  • EL主要的語法結構:
${sessionScope.user.sex}
  • [ ]與.運算符

    EL 提供“.“和“[ ]“兩種運算符來存取數據。

​ 當要存取的屬性名稱中包含一些特殊字符,如.或?等並非字母或數字的符號,就一定要使用“[ ]“。例如:

user.MyName{user.My-Name}應當改爲{user[“My-Name”] }

​ 如果要動態取值時,就可以用“[ ]“來做,而“.“無法做到動態取值。例如:

​ ${sessionScope.user[data]}中data 是一個變量

  • 變量

EL存取變量數據的方法很簡單,例如:${username}。它的意思是取出某一範圍中名稱爲username的變量。
​ 因爲我們並沒有指定哪一個範圍的username,所以它會依序從Page、Request、Session、Application範圍查找。
​ 假如途中找到username,就直接回傳,不再繼續找下去,但是假如全部的範圍都沒有找到時,就回傳null。
​ 屬性範圍在EL中的名稱

屬性範圍(jstl名稱) EL中的名稱
Page PageScope
Request RequestScope
Session SessionScope
Application ApplicationScope

我們也可以指定要取出哪一個範圍的變量:

範例 說明
${pageScope.username} 取出Page範圍的username變量
${requestScope.username} 取出Request範圍的username變量
${sessionScope.username} 取出Session範圍的username變量
${applicationScope.username} 取出Application範圍的username變量
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>jsp</title>
</head>
<body>
  <%
    application.setAttribute("name","application");
    session.setAttribute("name","session");
    request.setAttribute("name","request");
    pageContext.setAttribute("name","pageContext");
  %>
  <br>--------------------使用java語言---------------------------<br>
  application中的值:<%= application.getAttribute("name") %> <br>
  session中的值:<%= session.getAttribute("name") %> <br>
  request中的值:<%= request.getAttribute("name") %> <br>
  pageContext中的值:<%= pageContext.getAttribute("name") %> <br>

  <br>--------------------使用EL表達式---------------------------<br>
  application中的值:${applicationScope.name} <br>
  session中的值:${sessionScope.name} <br>
  request中的值:${requestScope.name} <br>
  pageContext中的值:${pageScope.name} <br>

  <br>----------------使用EL表達式,省略域對象---------------------<br>
  application中的值:${name} <br>

</body>
</html>

2、支持的運算

(1)數學運算

(2)比較運算 > gt < lt >= ge <= le == eq != !=

(3)邏輯預算 && || !

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>EL運算</title>
</head>
<body>
<%
    request.setAttribute("num1","12");
    request.setAttribute("num2","14");

    application.setAttribute("flag1",true);
    application.setAttribute("flag2",false);
%>
<br>--------------------使用java語言---------------------------<br>
<%
    String num1 = (String)request.getAttribute("num1");
    String num2 = (String)request.getAttribute("num2");
    int num3 = Integer.parseInt(num1) + Integer.parseInt(num2);
    
    boolean flag1 = (Boolean) application.getAttribute("flag1");
    boolean flag2 = (Boolean) application.getAttribute("flag2");
    boolean flag3 = flag1 && flag2;
    //輸出方式一
    out.write(Boolean.toString(flag3));
%>
<!-- 輸出方式二 -->
<h1><%=num3%></h1>

<br>--------------------使用EL表達式--------------------------<br>
<h1>${ requestScope.num1 + requestScope.num2 }</h1>
<h1>${ requestScope.num1 > requestScope.num2 }</h1>
<h1>${ applicationScope.flag1 && applicationScope.flag2 }</h1>

</body>
</html>

3、強調

1、注意當表達式根據名稱引用這些對象之一時,返回的是相應的對象而不是相應的屬性。例如:即使現有的 pageContext 屬性包含某些其他值,${pageContext} 也返回 PageContext 對象。

2、 注意 <%@ page isELIgnored=“true” %> 表示是否禁用EL語言,TRUE表示禁止.FALSE表示不禁止.JSP2.0中默認的啓用EL語言。

二、什麼是JSTL

JSTL全稱爲 JSP Standard Tag Library 即JSP標準標籤庫

JSTL作爲最基本的標籤庫,提供了一系列的JSP標籤,實現了基本的功能:集合的遍歷、數據的輸出、字符串的處理、數據的格式化等等!

1、爲什麼要使用JSTL

  • 實現了JSP頁面中的代碼複用(基於標籤庫原理,重複率較高的代碼塊支持複用,提高效率)
  • 書寫JSP頁面時可讀性更強(長得很像xml,方便前端查看和參與開發)

2、使用JSTL標籤庫步驟:

  1. 導入jstl.jar和standard.jar開發包
  2. 在JSP頁面中用tablib指令引入需要用到的JSTL標籤
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

3、重要標籤的使用

1、<c:set>

img

該標籤有5個屬性,用起來有稍微有些複雜了!現在要記住的就是:var屬性操作的是Integer、Double、Float、String等類型的數據,target屬性操作的是JavaBean或Map對象的數據,scope代表的是Web域,value是值,property是對象的屬性

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>  c:set  </title>
</head>
    <body>
        <!--
        相當於
        <%--  <%   --%>
        <%--   request.setAttribute("name","zhangsan");--%>
        <%--  %>  --%>
        -->
        <c:set scope="request" var="name" value="zhangsan" />
        通過JSTL標籤添加的作用域中的值:${requestScope.name}   <br>
        <c:set scope="application" var="name" value="lisi" />
        通過JSTL標籤添加的作用域中的值:${applicationScope.name}   <br>
        <c:set scope="request" var="name" value="wangwu" />
        通過JSTL標籤添加的作用域中的值:${requestScope.name}   <br>
        <c:set scope="page" var="name" value="zhaoliu" />
        通過JSTL標籤添加的作用域中的值:${pageScope.name}   <br>
    </body>
</html>

2、<c:if>

控制哪些內容能夠輸出到響應體

img

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title> c:if </title>
</head>
<body>
    <c:set scope="page" var="age" value="20"/>
    <br>------------------------------使用java語言-------------------------------------<br>
    <%
        if( Integer.parseInt((String)pageContext.getAttribute("age")) >= 18 ){
    %>
    輸入:歡迎光臨!
    <%  } else { %>
    輸入:未滿十八,不準入內!
    <%  }  %>
    <br>------------------------------使用JSTL標籤-------------------------------------<br>

    <c:if test="${ age ge 18 }">
        輸入:歡迎光臨!
    </c:if>
    <c:if test="${ age lt 18 }">
        輸入:未滿十八,不準入內!
    </c:if>
</body>
</html>

3、<c:choose>

if標籤沒有else的功能,如果需要類似於java中的if else流程就需要使用choose標籤。

choose標籤需要聯合when和otherwise標籤一起使用!

在jsp中進行多分支判斷,決定哪個內容寫入響應體

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title> c:choose </title>
</head>
<body>
    <c:set scope="page" var="age" value="6"/>
    <br>------------------------------使用java語言-------------------------------------<br>
    <%
        if( Integer.parseInt((String)pageContext.getAttribute("age")) == 18 ){
    %>
    輸入:您今年成年了
    <%  } else if( Integer.parseInt((String)pageContext.getAttribute("age")) > 18 ){ %>
    輸入:您已經成年了
    <%  }  else {%>
    輸出:您還是個孩子
    <% } %>
    <br>------------------------------使用JSTL標籤-------------------------------------<br>

    <c:choose>
        <c:when test="${age eq 18}">
            輸入:您今年成年了
        </c:when>
        <c:when test="${age gt 18}">
            輸入:您已經成年了
        </c:when>
        <c:otherwise>
            輸入:您還是個孩子
        </c:otherwise>
    </c:choose>
</body>
</html>

4、<c:forEach>

循環遍歷

使用方式

<c:forEach var="申明循環變量的名稱" begin="初始化循環變量" 
           end="循環變量可以接受的最大值" step="循環變量的遞增或遞減值">
    *** step屬性可以不寫,默認遞增1
    *** 循環變量默認保存在pageContext中
</c:forEach>

例子:

<%@ page import="com.zn.Student" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title> c:forEach </title>
</head>
<body>
    <%
        pageContext.setAttribute("students",new ArrayList(){{
            add(new Student("s1","zhangsan",16));
            add(new Student("s2","lisi",19));
            add(new Student("s3","wangwu",15));
        }});
        pageContext.setAttribute("stuMap", new HashMap(){{
            put("m1",new Student("s1","zhangsan",16));
            put("m2",new Student("s2","lisi",18));
            put("m3",new Student("s3","wangwu",15));
        }});
    %>
    <br>------------------------使用java語言------------------------------<br>
    <table>
        <tr><td>學號</td><td>姓名</td><td>年齡</td></tr>
        <%
            List<Student> stus =            (ArrayList<Student>)pageContext.getAttribute("students");
            for (int i = 0; i < stus.size(); i++) {
        %>
          <tr><td><%=stus.get(i).getSid()%></td>
              <td><%=stus.get(i).getName()%></td>
              <td><%=stus.get(i).getAge()%></td>
          </tr>
        <% } %>
    </table>
    
    <br>----------------------使用JSTL標籤讀取list-----------------------<br>
    <table>
        <tr><td>學號</td><td>姓名</td><td>年齡</td></tr>
        <c:forEach var="student" items="${students}">
        <tr><td>${student.sid}</td>
            <td>${student.name}</td>
            <td>${student.age}</td>
        </tr>
        </c:forEach>
    </table>

    <br>---------------------使用JSTL標籤讀取map------------------------<br>
    <table>
        <tr><td>學號</td><td>姓名</td><td>年齡</td></tr>
        <c:forEach var="student" items="${stuMap}">
            <tr>
                <td>${student.key}</td>
                <td>${student.value.sid}</td>
                <td>${student.value.name}</td>
                <td>${student.value.age}</td>
            </tr>
        </c:forEach>
    </table>

    <br>--------------使用JSTL標籤讀取指定for循環-----------------------<br>
    <select>
      <c:forEach var="item" begin="1" end="10" step="1">
          <option> ${item} </option>
      </c:forEach>
    </select>

</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章