The <c:if> is a JSTL core tag which is used for testing conditions. It is more or like an if statement in Java which evaluates a condition and executes a block of code if the result is true.
Syntax:
<c:if test="${condition}">
...
..
</c:if>
Example of <c:if> tag
Let's first create Student bean class:
package net.javaguides.jstl;
public class Student {
private String firstName;
private String lastName;
private boolean goldCustomer;
public Student(String firstName, String lastName, boolean goldCustomer) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.goldCustomer = goldCustomer;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean isGoldCustomer() {
return goldCustomer;
}
public void setGoldCustomer(boolean goldCustomer) {
this.goldCustomer = goldCustomer;
}
}
In this example, we will test if the student is a gold member or not using <c:if> tag:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="java.util.*,net.javaguides.jstl.Student" %>
<%
// just create some sample data ... normally provided by MVC
List<Student> data = new ArrayList<>();
data.add(new Student("Ramesh", "Fadatare", false));
data.add(new Student("John", "Cena", false));
data.add(new Student("Tom", "Cruise", false));
data.add(new Student("Tony", "Stark", false));
data.add(new Student("Prakash", "Jadhav", true));
pageContext.setAttribute("myStudents", data);
%>
<html>
<body>
<table border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Gold Customer</th>
</tr>
<c:forEach var="tempStudent" items="${myStudents}">
<tr>
<td>${tempStudent.firstName}</td>
<td>${tempStudent.lastName}</td>
<td>
<c:if test="${tempStudent.goldCustomer}">
Special Discount
</c:if>
<c:if test="${not tempStudent.goldCustomer}"> -
</c:if>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
Comments
Post a Comment