Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If-then-else inside a JSP expression?

Tags:

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.

like image 547
Xonatron Avatar asked Jan 25 '12 18:01

Xonatron


People also ask

Can we use if else in JSP?

Syntax of JSP if elseCode or set of executable statements that should be processed if second condition is true while the first one stands false. This condition should be executed if all conditions stand false. The if-else statement should be present on the JSP page.

How do you write an expression in JSP?

Expression tag is one of the scripting elements in JSP. Expression Tag in JSP is used for writing your content on the client-side. We can use this tag for displaying information on the client's browser.

How do you write if in 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.


1 Answers

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.

like image 93
Ivan Zarea Avatar answered Sep 29 '22 11:09

Ivan Zarea