The <c:if> tag won’t work for this

There’s no way to do exactly what we want using the <c:if> tag, because it doesn’t have an “else”. We can almost do it, using something like:

JSP using <c:if>, but it doesn’t work right...

<c:if test="${userPref=='performance'}" >
    Now you can stop even if you <em>do</em> drive insanely fast..
</c:if>
<c:if test="${userPref=='safety'}" >
    Our brakes won't lock up no matter how bad a driver you are.
</c:if>
<c:if test="${userPref=='maintenance'}" >
    Lost your tech job? No problem--you won't have to service these brakes
    for at least three years.
</c:if>

Note

But what happens if userPref doesn’t match any of these? There’s no way to specify the default headline?

<!-- continue with the rest of the page that EVERYONE should see -->

The <c:if> won’t work unless we’re CERTAIN that we’ll never need a default value. What we really need is kind of an if/else construct:[8]

JSP with scripting, and it does what we want

image with no caption

[8] Yes, we agree with you—there’s nearly always a better approach than chained if tests. But you’re just gonna have to suspend disbelief long enough to learn how this all works....

Get Head First Servlets and JSP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.