Open In App

JSTL Core <c:choose>, <c:when>, <c:otherwise> Tag

Last Updated : 15 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

JavaServer Pages Standard Tag Library (JSTL) is a tool for web application development in Java. It provides a collection of tags that allow developers to implement the logic as code for JSP applications. In this article, cover these tags with explanations to help you learn their functionality. JSTL tags <c:choose>, <c:when>, and <c:otherwise> are important for conditional logic in JSP applications.

They work in a similar way as if-else statements, following are the functionality associated with them.

  • <c:choose> Tag: It is used to create conditional operations. It has multiple <c:when> tags and an optional <c:otherwise> tag.
  • <c:when> Tag: It is used to check for a condition/expression and execute its body content if the condition is true. The condition can be any Java expression, such as a variable comparison, a logical expression, or a method call.
  • <c:otherwise> Tag: It is similar to the else statement of programming, its body content is executed if all of the conditions in the <c:when> tags are false.

JSTL Conditional Tags

JSTL provides a set of conditional tags similar to Java conditional keywords. The analogy with the Java programming keyword of these tags is listed below:

  • The <c:choose> tag acts as a switch statement
  • <c:when>, <c:otherwise> tags are used as if-else statements

The structure of a conditional block looks like this:

<c:choose>
<c:when test="${condition1}">
<!-- Code to execute if condition1 is true -->
</c:when>
<c:when test="${condition2}">
<!-- Code to execute if condition2 is true -->
</c:when>
<c:otherwise>
<!-- Default code to execute if none of the conditions are true -->
</c:otherwise>
</c:choose>

Now let’s see a few examples of JSTL tags in working to understand the syntax better.

Simple Conditional Check

In this example, we write a program that uses JSTL tags to determine whether the user is an adult or a minor.

<c:choose>
<c:when test="${user.age < 18}">
You are a minor.
</c:when>
<c:otherwise>
You are an adult.
</c:otherwise>
</c:choose>

Output:

If the user's age is less than 18, the output will be: "You are a minor." Otherwise, it will display "You are an adult."

Multiple Conditions

In this example, we will check if the user is a “manager”, or “admin”, etc using <c:when>, <c:otherwise> tags.

<c:choose>
<c:when test="${user.role == 'admin'}">
Welcome, Admin!
</c:when>
<c:when test="${user.role == 'manager'}">
Welcome, Manager!
</c:when>
<c:otherwise>
Welcome, User!
</c:otherwise>
</c:choose>

Output:

Depending on the user's role, it will display "Welcome, Admin!", "Welcome, Manager!", or "Welcome, User!".

Using Logical Operators

In this example, we will see the use of logical operators in conditions. It checks if the user is logged in and has the necessary permissions to access content.

<c:choose>
<c:when test="${user.isLoggedIn && user.hasPermission}">
You have access to content.
</c:when>
<c:otherwise>
Access denied.
</c:otherwise>
</c:choose>

Output:

If the user is logged in and has permission, it will display "You have access to content." Otherwise, it will show "Access denied."

Checking for Empty List

This example uses JSTL tags to check if a list is empty or contains data.

<c:choose>
<c:when test="${empty userList}">
The user list is empty.
</c:when>
<c:otherwise>
The user list contains data.
</c:otherwise>
</c:choose>

Output:

If the 'userList' is empty, it will output "The user list is empty." Otherwise, it will display "The user list contains data."

Examples of JSTL Tags

In this section, below are 4 examples covering real examples for <c:choose>, <c:when>, <c:otherwise> Tags. These real-world examples will help you to understand how JSTL’s conditional tags can be applied to make web application development in Java.

1. Online Shopping Cart

Using JSTL conditional tags determines the discount a user receives based on their total purchase amount:

HTML




<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Discount Checker</title>
</head>
<body>
    <c:set var="totalPurchaseAmount" value="120" />
    <c:choose>
        <c:when test="${totalPurchaseAmount >= 100}">
            You qualify for a 10% discount!
        </c:when>
        <c:when test="${totalPurchaseAmount >= 50}">
            You qualify for a 5% discount!
        </c:when>
        <c:otherwise>
            No discount available.
        </c:otherwise>
    </c:choose>
</body>
</html>


Output:

If the totalPurchaseAmount is $120, it will display "You qualify for a 10% discount!"
If the totalPurchaseAmount is $60, it will display "You qualify for a 5% discount!"
If the totalPurchaseAmount is $30, it will display "No discount available."

2. User Authentication

Using JSTL tags determine whether the user is logged in.

HTML




<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>User Authentication</title>
</head>
<body>
    <c:set var="user" scope="session">
        <c:set var="user.loggedIn" value="true" />
        <c:set var="user.username" value="JohnDoe" />
    </c:set>
    <c:choose>
        <c:when test="${user.loggedIn}">
            Welcome, ${user.username}! You have access to your profile.
        </c:when>
        <c:otherwise>
            Please log in to access your profile.
        </c:otherwise>
    </c:choose>
</body>
</html>


Output:

If the user is logged in, it will display a personalized greeting.
If the user is not logged in, it will prompt them to log in.

3. Permission Control

Using JSTL tags create a Permission Control program to determine the user’s reach to the content.

HTML




<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Permission Control</title>
</head>
<body>
    <c:set var="user" scope="session">
        <c:set var="user.role" value="admin" />
    </c:set>
    <c:choose>
        <c:when test="${user.role eq 'admin'}">
            You have full administrative privileges.
        </c:when>
        <c:when test="${user.role eq 'manager'}">
            You can manage user accounts.
        </c:when>
        <c:otherwise>
            Your role doesn't have specific privileges.
        </c:otherwise>
    </c:choose>
</body>
</html>


Output:

For an admin user, it will show "You have full administrative privileges."
For a manager user, it will display "You can manage user accounts."
For other roles, it will indicate that their role doesn't have specific privileges.

4. Weather Forecast

Using the JSTL tag, display the different messages as per the weather forecast.

HTML




<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Weather Forecast</title>
</head>
<body>
    <c:set var="weather" value="sunny" />
    <c:choose>
        <c:when test="${weather == 'sunny'}">
            It's a sunny day. Don't forget your sunscreen!
        </c:when>
        <c:when test="${weather == 'rainy'}">
            Grab your umbrella. It's raining!
        </c:when>
        <c:otherwise>
            Check the weather for today.
        </c:otherwise>
    </c:choose>
</body>
</html>


Output:

If the weather is "sunny," it will recommend wearing sunscreen.
If it's "rainy," it will suggest grabbing an umbrella.
For any other weather condition, it will prompt the user to check the weather.

Conclusion

The <c:choose>, <c:when>, and <c:otherwise> tags provide a way to implement conditional logic in JSP pages.

  • These tags allow you to write logic associated with the program into your application in a concise way, improving the overall quality of your web applications.
  • These tags help you to make your code more reader-friendly and easy to change by simplifying complex if-else conditions.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads