<c:choose>, <c:when>, <c:otherwise> Tags
The <c:choose>
tag functions similarly to the Java switch statement, used for making a choice among multiple options.
The switch statement has cases, and the <c:choose>
tag corresponds with <c:when>
. The switch statement has a default case, and the <c:choose>
tag has <c:otherwise>
.
Syntax
<c:choose>
<c:when test="<boolean>">
...
</c:when>
<c:when test="<boolean>">
...
</c:when>
...
...
<c:otherwise>
...
</c:otherwise>
</c:choose>
Attributes
The
<c:choose>
tag has no attributes.The
<c:when>
tag has only one attribute, listed in the table below.The
<c:otherwise>
tag has no attributes.
Attribute | Description | Required | Default Value |
---|---|---|---|
test | Condition | Yes | None |
Example
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>c:choose Tag Example</title>
</head>
<body>
<c:set var="salary" scope="session" value="${2000*2}"/>
<p>Your salary is : <c:out value="${salary}"/></p>
<c:choose>
<c:when test="${salary <= 0}">
Too bad.
</c:when>
<c:when test="${salary > 1000}">
Good salary, can live.
</c:when>
<c:otherwise>
Nothing.
</c:otherwise>
</c:choose>
</body>
</html>
Output:
Your salary is : 4000
Good salary, can live.