Maximum number of options within the JSTL <c:Choose> tag

Asked

Viewed 668 times

0

People recently was working with JSTL and I came across the following situation, I tried to add 3 tags when within a Choose tag and the last tag just doesn’t work, the code was like this:

<c:choose>
        <c:when test="${pagina != null}">
            <c:import url="${pagina}.jsp"></c:import>
        </c:when>
        <c:when test="${mensagem != null}">
            <br><p><c:out value="${mensagem}"></c:out></p>
        </c:when>
        <c:when test="${salvarTodosCertificados != null}">
            <p>Caso queira baixar todos os certificados em zip:</p> <br>
            Clique <a href="site?comando=gerarCertificado&quantos=todos">aqui</a>
        </c:when>
    </c:choose>

The maximum number of tags when I can put inside a Choose tag is actually 2?

I had to replace the above code with this:

    <c:choose>
        <c:when test="${pagina != null}">
            <c:import url="${pagina}.jsp"></c:import>
        </c:when>
        <c:when test="${mensagem != null}">
            <br><p><c:out value="${mensagem}"></c:out></p>
        </c:when>
    </c:choose>
    <c:choose>
        <c:when test="${salvarTodosCertificados != null}">
            <p>Caso queira baixar todos os certificados em zip:</p> <br>
            Clique <a href="site?comando=gerarCertificado&quantos=todos">aqui</a>
        </c:when>
    </c:choose>

This proceeds or I set something wrong or whatever?

1 answer

1


The number of clauses within the <c:choose> is, for practical purposes, unlimited.

But you don’t seem to understand the idea of <c:choose>. It works in a similar way to a if full of else ifs.

In the case of the first code, what you did is more or less this:

if (pagina != null) {
    // ...
} else if (mensagem != null) {
   // ...
} else if (salvarTodosCertificados != null) {
   // ...
}

The second, more or less, is:

if (pagina != null) {
    // ...
} else if (mensagem != null) {
   // ...
}
if (salvarTodosCertificados != null) {
   // ...
}

Note that each clause <c:when> is analogous to a if or else if. If you had one <c:otherwise>, it would be analogous to else.

In a structure if ... else if ... else if ..., only the first if which has the satisfied condition executes. Even if any of the ifs further down could also be satisfied, only the first that is satisfied runs. The same happens with the <c:choose>.

So your problem seems to be that you expected the <c:when> of condition salvarTodosCertificados != null was executed even when one of the conditions of one of the <c:when>s above is also true, which will not happen because of the fact that only the first is executed for which the condition is true. Or else, you expected the first two to be false when one of them is true. Or, you put your <c:when> in the wrong order.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.