学科分类
目录
Java Web

<c:choose>标签

​ 在程序开发中不仅需要使用if条件语句,还经常会使用if-else语句,为了在JSP页面中也可以完成同样的功能,Core标签库提供了<c:choose>标签,该标签用于指定多个条件选择的组合边界,它必须与<c:when>、<c:otherwise>标签一起使用。接下来,针对<c:choose>、<c:when>和<c:otherwise>这三个标签进行详细地讲解,具体如下:

1、标签

<c:choose>标签没有属性,在它的标签体中只能嵌套一个或多个<c:when>标签和零个或一个<c:otherwise>标签,并且同一个<c:choose>标签中所有的<c:when>子标签必须出现在<c:otherwise>子标签之前,其语法格式如下:

<c:choose>

  Body content(<when> and <otherwise> subtags)       

</c:choose>

2、标签

<c:when>标签只有一个test属性,该属性的值为布尔类型。test属性支持动态值,其值可以是一个条件表达式,如果条件表达式的值为true,就执行这个<c:when>标签体的内容,其语法格式如下:

<c:when test="testCondition">

  Body content

</c:when>

3、标签

<c:otherwise>标签没有属性,它必须作为<c:choose>标签最后分支出现,当所有的<c:when>标签的test条件都不成立时,才执行和输出<c:otherwise>标签体的内容,其语法格式如下:

<c:otherwise>

  conditional block

</c:otherwise>

​ 为了使初学者更好的学习<c:choose>、<c:when>和<c:otherwise>这三个标签,接下来将通过一个具体的案例来演示这些标签的使用,如例1所示。

例1 c_choose.jsp

 1  <%@ page language="java" contentType="text/html; charset=utf-8"

 2  pageEncoding="utf-8" import="java.util.*"%>

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

 4  <html>

 5  <head></head>

 6  <body>

 7    <c:choose>

 8      <c:when test="${empty param.username}">

 9        unKnown user.

 10     </c:when>

 11     <c:when test="${param.username=='itcast' }">

 12       ${ param.username} is manager.

 13     </c:when>

 14     <c:otherwise>

 15       ${ param.username} is employee.

 16     </c:otherwise>

 17   </c:choose>

 18 </body>

 19 </html>

打开IE浏览器,在地址栏中输入http://localhost:8080/chapter08/c_choose.jsp访问c_choose.jsp页面,此时,浏览器窗口中显示的结果如图1所示。

图1 c_choose.jsp

从图1可以看出,当使用http://localhost:8080/chapter08/c_choose.jsp地址直接访问c_choose.jsp页面时,浏览器中显示的信息为unknown user,这是因为在访问c_choose.jsp页面时并没有在URL地址中传递参数,因此<c:when test="${empty param.username}">标签中test属性的值为true,便会输出<c:when>标签体中的内容。如果在访问c_choose.jsp页面时传递一个参数username=itcast,此时浏览器窗口中显示的结果如图2所示。

图2 c_choose.jsp

从图2可以看出,浏览器中显示的信息为itcast is manager,这是因为在访问c_choose.jsp页面时传递了一个参数,当执行<c:when test="${empty param.username}">标签时,test属性的值为false,因此不会输出标签体中的内容,然后执行<c:when test="${param.username=='itcast' }">标签,当执行到该标签时,会判断test属性值是否为true,由于在URL地址中传递了参数username=itcast,因此test属性为true,就会输出该标签体中的内容itcast is manager,如果test属性为false,那么会输出<c:otherwise>标签体中的内容。

点击此处
隐藏目录