jstl <x:choose>, <x:when>, <x:otherwise>標籤

<x:choose>標籤的工作方式類似於Java中的switch語句。 這樣我們可以選擇多種替代方案。 在switch語句中有case語句,則<x:choose>標籤具有<x:when>標籤。以類似的方式,switch語句有default子句來指定默認操作,<x:choose>標籤有<x:otherwise>標籤作為默認子句。

屬性

  • <x:choose>標籤沒有任何屬性。
  • <x:when>標籤有以下列出的一個屬性。
  • <x:otherwise>標籤沒有任何屬性。

<x:if>標籤具有以下屬性 -

屬性 描述 必需 默認
select 要評估的條件

示例

以下示例將顯示如何使用<x:choose>標籤,編寫一個JSP檔:xml_choose.jsp 如下所示:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jstl xml:choose標籤示例</title>
</head>
<body>
    <div style="margin: auto; width: 90%">
        <h3>圖書資訊:</h3>

        <c:set var="xmltext">
        <books>
            <book>
              <name>Three mistakes of my life</name>
              <author>Newsu</author>
              <price>20</price>
            </book>
            <book>
              <name>Tomorrow land</name>
              <author>Bird</author>
              <price>190</price>
            </book>
            </books>
        </c:set>

        <x:parse xml = "${xmltext}" var = "output"/>
      <x:choose>
         <x:when select = "$output//book/author = 'Newsu'">
            Book is written by Newsu
         </x:when>

         <x:when select = "$output//book/author = 'Bird'">
            Book is written by Bird
         </x:when>

         <x:otherwise>
            Unknown author.
         </x:otherwise>
      </x:choose>
    </div>
</body>
</html>

運行上述專案代碼,得到以下結果如下 -


上一篇: Jstl教學 下一篇: JSP+MySQL實例