If-then-else inside a JSP expression?

Xonatron picture Xonatron · Jan 25, 2012 · Viewed 85.5k times · Source

Can you do an if-then-else statement inside a JSP expression?

EDIT : Specifically I was looking for a JSP solution, not a JSTL solution. But some JSTL solutions below are highly rated and are very welcome. Just please do not vote me down for a duplicate question because one has already been asked about JSTL.

Answer

Ivan Zarea picture Ivan Zarea · Jan 25, 2012

In JSP EL 2.0, you can do that using the ternary operator. For instance:

<option value="1" ${param.number == 1 ? 'selected' : ''}>First option</option>

What it does is it checks JSP's param's number variable. If it's 1, then selected is substituted. otherwise, nothing.