Conditions in JSTL

Posted on 19-02-2013 17:27 by graham
This short tutorial describes how to create conditional code in JSTL.

Including JSTL in your JSP page

The first thing you need to do is to include the JSTL tag library in your JSP page. To do this, place the following directive at the beginning of the JSP file:
<%@ taglib prefix="c" uri="" %>

Conditional structures in JSTL

In JSTL, two conditional structures are available. One is the <c:if ...> tag, the other one is <c:choose ...>.

Using <c:if ...>

Use <c:if ...> if you want to create a simple if ... condition, without any else clause:
<c:if test="${results > 0}">
The search has returned ${results} results.

Using <c:choose ...>

To simulate an if ... else ... condition, use the <c:choose ...> tag:
<c:when test="${results > 0}">
The search has returned some results

The search hasn't returned any results.

AND and OR conditions

The test attribute of the <c:if> and <c:choose> tag can contain a single condition, an alternative of conditions or a conjunctions.

For an AND conditions, use:
<c:if test="${age < 20 && sex == 'female'}">
Hey girl!

For an OR conditions, use:
<c:if test="${age < 25 || age > 65}">
You have a discount on bus fares!


Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems