if…else within JSP or JSTL

if…else within JSP or JSTL

I have a kind of open-ended question..
I want to have a HTML code based on condition (desktop/ipad)..say Condition 1/Condition 2
I want to have separate HTML snippets for each of these conditions…
if (Condition 1)
Some HTML code for con1
else if (Condition 2)
Some HTML code for con2

The condition I want to test (in JS) is;
var isiPad = navigator.userAgent.match(/iPad/i) != null;
if (isiPad)
{}
else
{}

Now this has to be implemented in a .jsp page…
So how do I do that? Should I use JSTL ?
What is the best way?
The main thing is that only corresponding code should actually be loaded/rendered
e.g. if condition 1 is true, the HTML code in condition 2 should not be executed at all (apart from being hidden in the browser)

Solutions/Answers:

Solution 1:

Should I use JSTL ?

Yes.

You can use <c:if> and <c:choose> tags to make conditional rendering in jsp using JSTL.

To simulate if , you can use:

<c:if test="condition"></c:if>

To simulate if…else, you can use:

<c:choose>
    <c:when test="${param.enter=='1'}">
        pizza. 
        <br />
    </c:when>    
    <c:otherwise>
        pizzas. 
        <br />
    </c:otherwise>
</c:choose>

Solution 2:

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.

Solution 3:

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.

Solution 4:

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>

Solution 5:

<%@ 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>

Solution 6:

simple way :

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