I want to output some HTML code based on some condition in a JSP file.
if (condition 1) { Some HTML code specific for condition 1 } else if (condition 2) { Some HTML code specific for condition 2 }
How can I do that? Should I use JSTL?
The if...else block starts out as an ordinary Scriptlet, but the Scriptlet is closed at each line with HTML text included between the Scriptlet tags.
You can use <c:if> and <c:choose> tags to make conditional rendering in jsp using JSTL.
The < c:if > tag is used for testing the condition and it display the body content, if the expression evaluated is true. It is a simple conditional tag which is used for evaluating the body content, if the supplied condition is true.
The prefix of core tag is c. Function tags. The functions tags provide support for string manipulation and string length. The URL for the functions tags is http://java.sun.com/jsp/jstl/functions and prefix is fn. Formatting tags.
Should I use JSTL ?
Yes.
You can use <c:if>
and <c:choose>
tags to make conditional rendering in jsp using JSTL.
To simulate if , you can use:
<c:if test="condition"></c:if>
To simulate if...else, you can use:
<c:choose> <c:when test="${param.enter=='1'}"> pizza. <br /> </c:when> <c:otherwise> pizzas. <br /> </c:otherwise> </c:choose>
If you just want to output different text, a more concise example would be
${condition ? "some text when true" : "some text when false"}
It is way shorter than c:choose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With