Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if...else within JSP or 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?

like image 979
copenndthagen Avatar asked May 09 '11 10:05

copenndthagen


People also ask

How to use if else condition in JSP page?

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.

Which of the following tags is used to conditions in JSP?

You can use <c:if> and <c:choose> tags to make conditional rendering in jsp using JSTL.

Which of these is a valid JSTL if tag?

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.

What is c tag in JSP?

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.


2 Answers

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> 
like image 60
jmj Avatar answered Sep 20 '22 19:09

jmj


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.

like image 22
KIR Avatar answered Sep 21 '22 19:09

KIR