JSTL的標籤及使用,包含例項

沈啟之路發表於2018-08-06

JSTL的使用介紹:

想要使用JSTL,首先需要給專案匯入JSTL的包(jstl.jar和standard.jar)。
在jsp頁面上新增這樣一行程式碼:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

JSTL的主要標籤有:
表示式標籤:out標籤、set標籤、remove標籤、catch標籤。
流程標籤:if標籤、choose標籤、when標籤、otherwise標籤。
迴圈標籤:forEach標籤、forTokens標籤。
URL標籤:import標籤、url標籤、redirect標籤。

他們的使用方法如下:
out標籤:輸出一個值。

<c:out value="${num }"></c:out>

set標籤:定義一個變數,var變數名,value變數值。

<c:set var="age" value="90"></c:set>

remove標籤:移除一個屬性。

<c:remove var="num"/>

catch標籤:丟擲一個異常,catchException為丟擲的異常名。

<c:catch var="catchException">
    <%
        int x = 5 / 0;
    %>
</c:catch>

if標籤:if判斷,寫在test中。

<c:if test="${num>10 }">
    標籤體的內容得到了輸出
</c:if>

choose標籤,when標籤,otherwise標籤:choose表示選擇,when表示判斷,otherwise表示除了上述情形以外的其他狀況。滿足條件顯式出來,不滿足不顯示。

<c:choose>
    <c:when test="${age>95 }">
        國家每月每人700
    </c:when>
    <c:when test="${age>80 }">
        國家每月每人150
    </c:when>
    <c:when test="${age>60 }">
        養老金自備
    </c:when>
    <c:otherwise>
        努力賺錢
    </c:otherwise>
</c:choose>

forEach標籤:迴圈遍歷,items 需要迴圈展現的資料,var代表當前遍歷項的變數名。 begin 開始條件 end 結束條件(用於擷取) 。step 步長(隔幾個輸出一下)。delims=”|,”使用,|分割。varStatus設定變數名,該變數用於存放集合中元素的資訊。

<c:forEach var=”user” items=”${userList }” varStatus=”StatusName” begin=”begin” end=”end” step=”step”>
    <tr>
        <td>${user.id }</td>
        <td>${user.name }</td>
        <td>${user.email }</td>
        <td>修改</td>
    </tr>
</c:forEach>

forTokens標籤:

<c:forTokens items="Zara,nuha,roshy" delims="," var="name">
   <c:out value="${name}"/><p>
</c:forTokens>

import標籤:動態載入外部容器的內容。

<c:import var="data" url="http://www.baidu.com"/>

url標籤:用於寫一個連結,param表示需要傳入的引數。

<a href="
<c:url value="/delete">
    <c:param value="${user.id }" name="userId"></c:param>
    <c:param value="${user.name }" name="userName"></c:param>
</c:url>
">

redirect標籤:重定向到某一個頁面。

<c:redirect url="jstl2.jsp"></c:redirect>

相關文章