Ternary Operator in JSP 2.0 Expression Language(EL)

A very common need in a JSP page is to include a piece of template text only if a certain condition is true.
With JSP 1.2 and JSTL 1.1, this is typically done using a block, but that’s a very verbose solution.

also read:

JSP 2.0 adds a new conditional operator to the Expression Language(EL) to deal with this case in a more elegant way.The
conditional operator exists in many programming languages (for instance, in Java, C, and JavaScript), so you may have seen it before. It takes a Boolean condition and one result to use if the condition is true and another if it’s false. I use a very simple example to demonstrate the usage :

1) File Name : firstPage.jsp

<html>
	<head>
	<script language="javascript">
		function checkNumber()
		{
			var number = document.forms['myForm'].numberTxt.value;
			if(number < 1 || number > 5 || isNaN(number))
			{
				alert("Please enter a number between 1 and 5");
				return false;
			}
		}
	</script>
	</head>
	<body>
		<form name="myForm" method="post" action="secondPage.jsp">
			Please enter a number between 1 and 5 and press the Ok button :
			<br />
			<input type="text" id="numberTxt" name="numberTxt" />
			<br />
			<input type="submit" name="btnSubmit" value="Ok" onclick="return(checkNumber());"/>
		</form>
	</body>
</html>

2) File Name : secondPage.jsp

<html>
<head>
</head>
<body>
	<form>
		<select>
			<option value="1" ${param.numberTxt == 1 ? 'selected' : ''}>Suresh</option>
			<option value="2" ${param.numberTxt == 2 ? 'selected' : ''}>Ramesh</option>
			<option value="3" ${param.numberTxt == 3 ? 'selected' : ''}>Naresh</option>
			<option value="4" ${param.numberTxt == 4 ? 'selected' : ''}>Rajeev</option>
			<option value="5" ${param.numberTxt == 5 ? 'selected' : ''}>Pawan</option>
		</select>
	</form>
</body>
</html>

Explantion:

In the first page I enter a number between 1 and 5 and click the submit button. The request is submitted to the second page. In the second page I have used a drop down list to display some names. Out of these names one of them gets selected depending on what value is entered in the first page.

I use the param expressions language implicit object,which contains a map of request parameters, to fetch the value of numberTxt parameter. The value is compared with fixed constants for each option tag. If an expression returns true, the string selected is replaced in its place. In case the expression returns false blank string is replaced.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better