Open In App

JSTL Core <c:if> Tag

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

To control the execution sequence within a JSP page, use the conditional JSTL Core <c:if> tag. When an expression is evaluated by the tag, the body of the tag is only included if the expression is determined to be true.

Syntax <c:if> tag

<c:if test="${expression}">
...
</c:if>

The test property, which identifies the expression to be assessed, is necessary. Any legal EL expression is acceptable. The tag’s body is included in the output if the expression returns true. If not, the tag’s body is ignored.

Several more properties are also supported by the c:if> tag, including:

  • var: Creates a variable with the expression’s value.
  • scope: Describes the variable’s range of application.
  • varScope: Defines the parameters of the variable that the var attribute creates.

Why use JSTL Core <c:if> Tag

  • Easier to read and change the code
  • Lower probability of errors
  • More options for regulating how code is run
  • Quicker page loads
  • Performs on several servers

Building a Price Calculator

The objective is to develop a price calculator that enables users to enter the quantities of different things they desire to buy and view a total that includes any applicable discounts.

index.jsp Page setup

HTML




<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Price Calculator</title>
    ...
</head>
<body>


Setup of the user interface

  • Item Selection: The user is given a form to fill out where they can enter amounts for a number of different things, including red shirts, blue pants, red hats, blue coats, and green socks.

HTML




<h2>Item Order Form</h2>
<form action="index.jsp" method="post">
    Number of Red Shirts: <input type="text" name="redShirts" value="0"><br>
    ...
    <input type="submit" value="Calculate">
</form>


  • Navigation Bar: A navigation bar is located at the top of the page and allows customers to filter and view products depending on their color. It’s an extra function that helps with product selection and enhances the user experience.

HTML




<div id="navbar">
    <a href="<c:url value='products.jsp'/>">All Products</a>
    ...
</div>


Underlying logic

  • Item Pricing: Every item has a fixed price that is set using the c:set tag. A red shirt, for instance, costs $4.

HTML




<c:set var="redShirtPrice" value="4" />
...
<c:set var="greenSocksPrice" value="1.2" />


  • Total Price Calculation: After submitting the form, the total price is determined by taking into account the amount and cost of each item that the user has selected.

HTML




<c:if test="${not empty param.redShirts}">
    <c:set var="totalPrice" value="${param.redShirts * redShirtPrice + ...}" />
</c:if>


  • Discount Application: The calculator incorporates logic to offer discounts in order to encourage large purchases. A user receives a 7% discount if they buy between 10 and 25 goods. They receive a 10% discount if they buy 26 to 50 goods. Customers are encouraged to make more purchases as a result.

HTML




<c:set var="discount" value="0" />
<c:if test="${totalItems > 10 && totalItems <= 25}">
    <c:set var="discount" value="${totalPrice * 0.07}" />
</c:if>
...


  • Final Price Calculation: The total cost that the user must pay is calculated after any possible discounts have been applied.

HTML




<c:set var="finalPrice" value="${totalPrice - discount}" />


Feedback from users and display

  • Order Summary: An order summary is shown, outlining each item’s quantity, individual price, and subtotal in order to keep the process clear and user-friendly.

HTML




<h3>Order Summary:</h3>
<table border="1">
    ...
</table>


  • Total Amount and Discounts: The ultimate price (after any available discounts) is displayed beneath the summary. If there is a discount, it is highlighted so the user can see the savings.

HTML




<div>
    Total Price: $${finalPrice} 
    <c:if test="${discount > 0}">
        (Discount Applied: $${discount})
    </c:if>
</div>


Using c:if to render conditions

  • This project makes considerable use of the c:if> tag. The user experience is enhanced by making sure that calculations and summaries are only displayed when necessary.
  • For instance, only if the user has entered a quantity for redShirts, indicating they have interacted with the form, are the order summary and computations displayed. By doing this, the page is kept clutter-free until it is needed.

Conditional Rendering using <c:if>

HTML




<c:if test="${not empty param.redShirts}">
    ...
</c:if>


Product Sorting for Better UX

  • Despite not being directly related to pricing calculation, the top navigation bar enhances user experience. Users can view products in a certain color by clicking on links for that color. This function facilitates item selection and browsing.

HTML




<div id="navbar">
    <a href="<c:url value='products.jsp'/>">All Products</a>
    ...
</div>


The final index.jsp file will look like this

HTML




<!-- index.jsp -->
  
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Price Calculator</title>
    <style>
        #navbar {
            background-color: #333;
            overflow: hidden;
        }
  
        #navbar a {
            float: left;
            display: block;
            color: white;
            text-align: center;
            padding: 14px 16px;
            text-decoration: none;
        }
  
        #navbar a:hover {
            background-color: #ddd;
            color: black;
        }
    </style>
</head>
<body>
    <div id="navbar">
        <!-- All Products Link -->
        <a href="<c:url value='products.jsp'/>">All Products</a>
          
        <!-- Red Products Link -->
        <a href="<c:url value='products.jsp'>
            <c:param name="color" value="red"/>
        </c:url>">Red Products</a>
          
        <!-- Blue Products Link -->
        <a href="<c:url value='products.jsp'>
            <c:param name="color" value="blue"/>
        </c:url>">Blue Products</a>
          
    </div>
      
    <h2>Item Order Form</h2>
<form action="index.jsp" method="post">
    <!-- Input fields for items -->
    Number of Red Shirts: <input type="text" name="redShirts" value="0"><br>
    Number of Blue Pants: <input type="text" name="bluePants" value="0"><br>
    Number of Red Hats: <input type="text" name="redHats" value="0"><br>
    Number of Blue Jackets: <input type="text" name="blueJackets" value="0"><br>
    Number of Green Socks: <input type="text" name="greenSocks" value="0"><br>
    <input type="submit" value="Calculate">
</form>
  
<!-- Setting the item prices -->
<c:set var="redShirtPrice" value="4" />
<c:set var="bluePantsPrice" value="7.5" />
<c:set var="redHatPrice" value="2" />
<c:set var="blueJacketPrice" value="9" />
<c:set var="greenSocksPrice" value="1.2" />
  
<c:if test="${not empty param.redShirts}">
    <!-- Calculate total price based on item counts and prices -->
    <c:set var="totalPrice" value="${param.redShirts * redShirtPrice + param.bluePants * bluePantsPrice + param.redHats * redHatPrice + param.blueJackets * blueJacketPrice + param.greenSocks * greenSocksPrice}" />
      
    <!-- Calculate the total count of items -->
    <c:set var="totalItems" value="${param.redShirts + param.bluePants + param.redHats + param.blueJackets + param.greenSocks}" />
  
    <c:set var="discount" value="0" />
    <!-- Apply 7% discount if total items are between 10 to 25 -->
    <c:if test="${totalItems > 10 && totalItems <= 25}">
        <c:set var="discount" value="${totalPrice * 0.07}" />
    </c:if>
    <!-- Apply 10% discount if total items are between 26 to 50 -->
    <c:if test="${totalItems > 25 && totalItems <= 50}">
        <c:set var="discount" value="${totalPrice * 0.10}" />
    </c:if>
  
    <!-- Calculate the final price after discount -->
    <c:set var="finalPrice" value="${totalPrice - discount}" />
  
    <!-- Order Summary -->
    <h3>Order Summary:</h3>
    <table border="1">
        <tr>
            <th>Item</th>
            <th>Quantity</th>
            <th>Price per Item ($)</th>
            <th>Subtotal ($)</th>
        </tr>
        <tr>
            <td>Red Shirts</td>
            <td>${param.redShirts}</td>
            <td>${redShirtPrice}</td>
            <td>${param.redShirts * redShirtPrice}</td>
        </tr>
        <tr>
            <td>Blue Pants</td>
            <td>${param.bluePants}</td>
            <td>${bluePantsPrice}</td>
            <td>${param.bluePants * bluePantsPrice}</td>
        </tr>
        <tr>
            <td>Red Hats</td>
            <td>${param.redHats}</td>
            <td>${redHatPrice}</td>
            <td>${param.redHats * redHatPrice}</td>
        </tr>
        <tr>
            <td>Blue Jackets</td>
            <td>${param.blueJackets}</td>
            <td>${blueJacketPrice}</td>
            <td>${param.blueJackets * blueJacketPrice}</td>
        </tr>
        <tr>
            <td>Green Socks</td>
            <td>${param.greenSocks}</td>
            <td>${greenSocksPrice}</td>
            <td>${param.greenSocks * greenSocksPrice}</td>
        </tr>
    </table>
  
    <!-- Display the final price and discount (if applied) -->
    <div>
        Total Price: $${finalPrice} 
        <c:if test="${discount > 0}">
            (Discount Applied: $${discount})
        </c:if>
    </div>
</c:if>
  
</body>
</html>


Video Demo

Demo of How the Price Calculator is Constructed with the Aid of JSTL Core <c:if> Tag.

Demo--JSTL-Cif-tag

Frequently Asked Questions (FAQs)

1. What is the purpose of the JSTL Core c:if> Tag?

The execution order of a JSP page is managed by the JSTL Core c:if> Tag. If an expression is evaluated and found to be true, only then is the body of the tag included in the output.

2. Why is the JSTL Core c:if> Tag preferable to other techniques?

You can make your code simpler to read and alter by using the JSTL Core c:if> Tag. It lowers the likelihood of mistakes, gives developers more control over how code is run, guarantees quicker page loads, and is interoperable with a variety of servers.

3. What is the Price Calculator’s main objective?

Users can enter the quantity of various things they desire to purchase using the price calculator. The final step is to compute the overall cost while taking into account any available quantity-based discounts.

4. How do discounts get applied in the price calculator?

Discounts are given in accordance with quantity. A user receives a 7% discount if they purchase between 10 and 25 goods. They get a 10% discount if they buy between 26 and 50 goods.

5. Where can I get instructions on how to build up a project using the c:if> Tag?

You can refer to this article for a step-by-step explanation of how to set up the project using the c:if> Tag. A video demo is also available that shows how the Price Calculator was built using the JSTL Core c:if> Tag.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads