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?
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?
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>
The construct for this is:
<c:choose>
<c:when test="${..}">...</c:when> <!-- if condition -->
<c:when test="${..}">...</c:when> <!-- else if condition -->
<c:otherwise>...</c:otherwise> <!-- else condition -->
</c:choose>
If the condition isn't expensive, I sometimes prefer to simply use two distinct <c:if tags - it makes it easier to read.
If you want to do the following by using JSTL Tag Libe, please follow the following steps:
[Requirement] if a number is a grater than equal 40 and lower than 50 then display "Two digit number starting with 4" otherwise "Other numbers".
[Solutions]
1. Please Add the JSTL tag lib on the top of the page.`
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>`
2. Please Write the following code
`
<c:choose>
<c:when test="${params.number >=40 && params.number <50}">
<p> Two digit number starting with 4. </p>
</c:when>
<c:otherwise>
<p> Other numbers. </p>
</c:otherwise>
</c:choose>`
<c:choose>
<c:when test="${not empty userid and userid ne null}">
<sql:query dataSource="${dbsource}" var="usersql">
SELECT * FROM newuser WHERE ID = ?;
<sql:param value="${param.userid}" />
</sql:query>
</c:when>
<c:otherwise >
<sql:query dataSource="${dbsource}" var="usersql">
SELECT * FROM newuser WHERE username = ?;
<sql:param value="${param.username}" />
</sql:query>
</c:otherwise>