The ternary operator and JSP

This interesting bit of JSTL for JSP is worth writing about.

Background: The ternary operator allows you to combine an if-then-else statement into one line using a bunch of symbols. It makes code a bit harder to read, but it also makes it look cool.

I can turn this:

<c:choose>
<c:when test="{not empty somevariable}">
  not empty
</c:when>
<c:otherwise>
  empty
</c:otherwise>
<c:choose>

into this:

<c:out value="${not empty somevariable ? 'not empty' : 'empty'}" />

It even parses variables for output:

<c:out value="${not empty somevariable ?  somevariable: 'empty'}" />

And you don’t even need the c:out:

${not empty somevariable ?  somevariable: 'empty'}

Old hat yes, but I thought an interesting tidbit to write about!

Advertisements

4 thoughts on “The ternary operator and JSP

  1. He is one for youis is possible to correctly write something like this?${not empty somevariable ? somevariable + ‘xxx’: ’empty’}Is is possible to do this kind of concatenation with just EL?

  2. Hi Geoffrey, I am really sorry, I just noticed this comment! I believe it is possible to do that sort of concatenation inside the ? and : sections. Did you figure this out? I can post an example if you like.

  3. Yes Steve your example for “${not empty somevariable ? somevariable + ‘xxx’: ’empty’}” pattern definitely helps me, plz write one. Thanks in advance.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s