Puis-je jeter avec exception JSTL dans une balise JSP personnalisée lorsqu'un attribut est invalide?

StackOverflow https://stackoverflow.com/questions/8845884

Question

Je fais une balise JSP. Je passe un paramètre de type à la balise.

Le regard de code comme ceci:

<%@ attribute name="type" require="true" %>
<c:choose>
    <c:when test="${type eq 'even'}">
        <c:set var="remainder" value="0" />
    </c:when>
    <c:when test="${type eq 'odd'}">
        <c:set var="remainder" value="1" />
    </c:when>
    <c:otherwise>
        <%-- Want to throw exception!! --%>
    </c:otherwise>
</c:choose>

Je veux lancer une exception si je passe une mauvaise valeur. Quand je cherchai à propos de ce sujet, je viens de trouver cette . Je ne peux pas lancer une exception normale dans JSTL?

Était-ce utile?

La solution

Just throw to notice the problem immediately

Who would "notice" ? That exception can only be caught by the container and it will result in some "500 Internal Server Error" page (or some custom error page you define).

If that's what you really want, you can define a custom tag that will just perform "throw new WhateverException()", and then make use of your custom taglib like: <mytaglib:reportError/>, as the standard core taglib did not consider throwing an exception would ever be desirable for anyone.

Autres conseils

I have decided to revive and edit a deleted answer which looked partially correct.

You can throw an exception by adding it in a scriptlet like so:

<c:choose>
    <c:when test="${type eq 'even'}">
        <c:set var="remainder" value="0" />
    </c:when>
    <c:when test="${type eq 'odd'}">
        <c:set var="remainder" value="1" />
    </c:when>
    <c:otherwise>
        <% if (true) throw new Exception("Wrong type"); %>
    </c:otherwise>
</c:choose>

However, your jsps are supposed to be part of your "view" layer so you should really try to keep your logic (including throwing the exception) in your servlets.

Note the if (true) statement. It is a trick becase the compiler will complain about "unreachable code" if you just drop the exception scriptlet into your code.

I would just use a custom EL function or tag which systematically throws an exception, or displays a big red div with the error message, or both

${myFn:illegalState("the type must be odd or even but it is " ${type})}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top