If else and switch in JSP using JSTL

How we can perform decision-making operations on the JSP page without using a scriptlet tag. JSTL is a rich library that contains tags to perform if-else and switch operations. In this JSTL tutorial, let’s do some hands-on with JSTL to perform decision-making operations.

IF condition in JSTL

In order to add, If condition in JSTL we will use <c:if test=""></c:if> tag that is the part of core taglib <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Here, test attribute is used to define the conditional statement.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<h2>IF ELSE and SWITCH operations in JSTL</h2>

<c:set var="name" value="codebun"></c:set>

<c:if test="${name=='codebun'}">

<p>This Para from Codebun While If condition is True</p>

</c:if>
</body>
</html>

In the above code, We have set a variable with the name as “name” and the value is “codebun”. In the next line there is an If tag with the conditional statement test="${name=='codebun'}"

It means, If the name is equal to ‘codebun’ then only the next statement <p>This Para from Codebun While If condition is True</p> will be printed on-page. otherwise, it will print nothing.

Else in JSTL

There is no else tag to perform else operation in JSTL. we can use only if statement there are other tags are available to perform else part like choose tag that we will see under the Switch section.

Switch Case in JSTL

We can implement Switch conditions in JSTL by using <c:choose></c:choose> tag. but alone with choose tag we have to takecare of two more tag that is <c:when></c:when> and<c:otherwise></c:otherwise>

Let’s solve a decision-making problem using these tags in JSTL. In the below code example, We are taking value from a URL parameter with the name “carName “ and will print the message according to the car name.

<c:choose></c:choose> is parent tag that contains <c:when></c:when> and<c:otherwise></c:otherwise> tags.

<c:when></c:when> tag is used to define the conditions and <c:otherwise></c:otherwise> tag is used to enter the default condition or incase of invalid values from URL.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<h2>IF ELSE and SWITCH operations in JSTL</h2>

<c:choose>

<c:when test="${param.carName == 'bmw'}">
    Driving BMW
</c:when>

<c:when test="${param.carName == 'reno'}">
    Driving Reno
</c:when>

<c:when test="${param.carName == 'audi'}">
    Driving Audi
</c:when>

<c:otherwise>
  
  Driving nothing I at Home......

</c:otherwise>


</c:choose>



</body>
</html>