Reputation: 121
I want to make an if statment in JSTL .. Here is what i want to make:
<c:set var="sex" value="${param.sex}"/>
<c:if test="$(param.sex=='male')" >
//set the sex to zero
</c:if>
<c:if test="$(param.sex=='female')" >
//set the sex to one
</c:if>
and then use the sex in the where clause like this
<sql:query dataSource="${dbcon}" var="result">
select firstname,lastname from members where sex = ?
<sql:param value="${sex}"></sql:param>
Upvotes: 3
Views: 678
Reputation: 1338
You don't need to do the zero/one bit, if you aren't using the ${sex} variable anywhere else other than your sql:query. Your problem can collapse from:
<c:set var="sex" value="${param.sex}"/>
<c:if test="$(param.sex=='male')" >
//set the sex to zero
</c:if>
<c:if test="$(param.sex=='female')" >
//set the sex to one
</c:if>
...
<sql:query dataSource="${dbcon}" var="result">
select firstname,lastname from members where sex = ?
<sql:param value="${sex}">
</sql:param>
Down to just this:
<sql:query dataSource="${dbcon}" var="result">
select firstname,lastname from members where sex = ?
<sql:param value="${param.sex == 'male' ? 0 : 1}">
</sql:param>
The point being that you can use param.sex directly in the sql:query statement, and you can use the "ternary operator" instead of using an if statement in this situation.
Google for more on the "JSTL ternary operator" or take a look here (scroll down to Ternary Operations): http://davidensinger.com/2014/07/fun-with-jstl-in-jsps/
UPDATE
To see the ternary operator in action and make sure the param.sex value is the value you expect you can just type this:
${param.sex == 'male' ? 0 : 1}
On a blank line and it should print either a 0 or 1 to your screen.
Upvotes: 1
Reputation: 654
select firstname,lastname from members where sex =<%= Enter variable name assumed for sex in this EL %>
Upvotes: 0