Search code examples
jspforeachjstl

JSTL c:choose and mutiple c:forEach, c:if issue


I'm trying to use <c:forEach> and <c:if> in <c:choose>. My original plan was when list size is 0 then it shows "there is no result" and if it is not it shows the things in the list. However, it seems like whenever I use <c:choose>, the page does not load properly, even ${param} does not catch the parameters.

Here is my code. The first part is where I use ${param}, it works perfectly when there is no <c:choose>.

<select class="myselect" id="type_size" name="type_size">
        <c:if test="${param.type_size eq null}">
           <c:forEach var="i" begin="2" end="6" step="2">
               <option value="${i}">${i}</option>
           </c:forEach>
        </c:if>
    <c:if test="${param.type_size ne null}">
        <option value=" ${param.type_size}"> ${param.type_size}</option>
    </c:if>
</select>

Here is the code with <c:choose> <c:forEach> so on

<div class="container>
<c:if test="${item[0].getRoom_no eq null}">
    <div class="row_room">
        <div class="item">
            There is no result available at this moment.
        </div>
    </div>
</c:if>   
  <c:if test="${item[0].getRoom_no ne null}">    
    <c:forEach var="tmp" items="${item}" varStatus="idx">
    <c:if test="${idx.index%3==0}">
  <div class="row"> 
   </c:if>
  <div class="item"> 
 <div class="media">
 <img src="resources/room_img/${tmp.getRoom_img01()}"/>
  </div><!-- media end -->
    <div class="row">
       </c:if>
          <h4>${tmp.getRoom_no()}  |  ${tmp.getType_name()} </h4>
            <button type="button" onclick="location.href='roomView?checkin=${param.checkin}&checkout=${param.checkout}&type_size=${param.type_size}&room_no=${tmp.getRoom_no()}'">reserve</button>
     </div><!-- row end -->
   <c:if test="${idx.index%3 == 2 || idx.index == end}">
     </div>
    </div><!-- row end -->
    </c:if>
    </c:forEach> 
    </c:otherwise>
   </c:if>
   </c:choose>
   </div><!-- container end -->

Solution

  • Some syntax errors i found:

    • Missing closing quotes: <div class="container> should be <div class="container">.
    • I don't see any opening tags for <c:choose> and <c:otherwise>. The <c:when> is also missing.

    The basic construct of choose-when-otherwise is:

    <c:choose>
        <c:when test="${something eq 0}">
           something is zero
        </c:when>
        <c:when test="${something gt 0}">
            something is positive
        </c:when>
        <c:otherwise>
            something is negative
        </c:otherwise>
    </c:choose>
    

    There could be more errors, but i can't see because of the bad tag indents/format.
    This is also means that the code is in this form not maintainable.
    Consider moving the if-else logic to a servlet/class and let the jsp just display the data.