[jsp] if...else within JSP or JSTL

I want to output some HTML code based on some condition in a JSP file.

if (condition 1) {
    Some HTML code specific for condition 1
}
else if (condition 2) {
    Some HTML code specific for condition 2
}

How can I do that? Should I use JSTL?

This question is related to jsp if-statement jstl

The answer is


The construct for this is:

<c:choose>
   <c:when test="${..}">...</c:when> <!-- if condition -->
   <c:when test="${..}">...</c:when> <!-- else if condition -->
   <c:otherwise>...</c:otherwise>    <!-- else condition -->
</c:choose>

If the condition isn't expensive, I sometimes prefer to simply use two distinct <c:if tags - it makes it easier to read.


In case you want to compare strings, write the following JSTL :

<c:choose>
    <c:when test="${myvar.equals('foo')}">
        ...
    </c:when>
    <c:when test="${myvar.equals('bar')}">
        ...
    </c:when>
    <c:otherwise>
        ...
    </c:otherwise>
</c:choose>

<c:choose>
<c:when test="${not empty userid and userid ne null}">
      <sql:query dataSource="${dbsource}" var="usersql">
                SELECT * FROM newuser WHERE ID = ?;
                <sql:param value="${param.userid}" />
      </sql:query>
 </c:when>
 <c:otherwise >
       <sql:query dataSource="${dbsource}" var="usersql">
                 SELECT * FROM newuser WHERE username = ?;
                 <sql:param value="${param.username}" />
       </sql:query>                              
  </c:otherwise>


If you just want to output different text, a more concise example would be

${condition ? "some text when true" : "some text when false"}

It is way shorter than c:choose.


In case you want to compare strings, write the following JSTL:

<c:choose>
    <c:when test="${myvar.equals('foo')}">
        ...
    </c:when>
    <c:when test="${myvar.equals('bar')}">
        ...
    </c:when>
    <c:otherwise>
        ...
    </c:otherwise>
</c:choose>

If you want to do the following by using JSTL Tag Libe, please follow the following steps:

[Requirement] if a number is a grater than equal 40 and lower than 50 then display "Two digit number starting with 4" otherwise "Other numbers".

[Solutions]

1. Please Add the JSTL tag lib on the top of the page.`
     <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>`

2. Please Write the following code
`
<c:choose>
       <c:when test="${params.number >=40 && params.number <50}">
              <p> Two digit number starting with 4. </p>
       </c:when>
       <c:otherwise>
              <p> Other numbers. </p>
       </c:otherwise>
  </c:choose>`

simple way :

<c:if test="${condition}">
    //if
</c:if>
<c:if test="${!condition}">
    //else
</c:if>

You can write if-else condition inside <% %> in jsp pages and html code outside of <% %>

For example:

   <%
        String username = (String)session.getAttribute("username");
        if(username==null)  {
    %>            
        <p> username is null</p> //html code
    <%
        } else {
    %>
        <p> username is not null</p> //html code
    <%
        }
    %>

<c:if test="${any_cond}" var="condition">
    //if part
</c:if>
<c:if test="${!condition}">
    //else part
</c:if>

<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<c:set var="isiPad" value="value"/>
<c:choose>
   <!-- if condition -->
   <c:when test="${...}">Html Code</c:when> 
   <!-- else condition -->
   <c:otherwise>Html code</c:otherwise>   
</c:choose>

<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<c:set var="val" value="5"/>
<c:choose> 
  <c:when test="${val == '5'}">
    Value is 5
  </c:when>
  <c:otherwise>
    Value is not 5
  </c:otherwise>
</c:choose>

Examples related to jsp

Difference between request.getSession() and request.getSession(true) A child container failed during start java.util.concurrent.ExecutionException The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path Using if-else in JSP Passing parameters from jsp to Spring Controller method how to fix Cannot call sendRedirect() after the response has been committed? How to include js and CSS in JSP with spring MVC How to create an alert message in jsp page after submit process is complete getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever? How to pass the values from one jsp page to another jsp without submit button?

Examples related to if-statement

How to use *ngIf else? SQL Server IF EXISTS THEN 1 ELSE 2 What is a good practice to check if an environmental variable exists or not? Using OR operator in a jquery if statement R multiple conditions in if statement Syntax for an If statement using a boolean How to have multiple conditions for one if statement in python Ifelse statement in R with multiple conditions If strings starts with in PowerShell Multiple conditions in an IF statement in Excel VBA

Examples related to jstl

Iterating through a List Object in JSP How to get a index value from foreach loop in jstl Get value from hashmap based on key to JSTL How to use if, else condition in jsf to display image Selected value for JSP drop down using JSTL Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core" java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config Adding external resources (CSS/JavaScript/images etc) in JSP Sun JSTL taglib declaration fails with "Can not find the tag library descriptor" How to do if-else in Thymeleaf?