开发者

How do I do "nested if" in JSTL for Java JSP?

I want to do something like the following:

<c:choose>
    <c:when test=开发者_如何学Go"${empty example1}">
    </c:when>
    <c:otherwise>
        <c:when test="${empty example2}">
        </c:when>
        <c:otherwise>
        </c:otherwise>              
    </c:otherwise>
</c:choose>

Is this even possible? I get an exception thrown when trying to run.

Thank you.


You need to do it more like this:

<c:choose>
    <c:when test="${empty example1}"> 
        <!-- do stuff -->
    </c:when> 
    <c:otherwise> 
        <c:choose>
            <c:when test="${empty example2}"> 
                <!-- do different stuff -->
            </c:when> 
            <c:otherwise> 
                <!-- do default stuff -->
            </c:otherwise>
        </c:choose>
    </c:otherwise> 
</c:choose>

The verbosity shown here is a good example of why XML is a poor language for implementing multi-level conditional statements.


You can use multiple <c:when>s in a <c:choose>.

<c:choose>
    <c:when test="${empty example1}">
    </c:when>
    <c:when test="${empty example2}">
    </c:when>
    <c:otherwise>
    </c:otherwise>              
</c:choose>


I agree with @BalusC--you can simplify the statement. Remember that c:when statements are mutually exclusive, like if-else if blocks.

The JSTL 1.2 spec states that c:choose must be the parent of at least one c:when statement, and that c:when must always precede at least one c:otherwise statement with the same immediate parent. Essentially, that also means that every c:when must have a c:otherwise following it inside a c:choose, and a c:choose must surround any c:when + c:otherwise. From what I can see, the spec does not refer to nesting c:choose elements, so I don't know whether it works--but I don't think you will ever be forced into nesting them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜