JSF EL - replace null with default value
Asked Answered
N

2

9

Is there a way to replace null with a default value in JSF EL expressions, sort of like the Oracle NVL function?

I know I can do something like

#{obj == null ? 'None' : obj.property}

But was hoping there is an automatic way to do it so I'm not copy/pasting the same expression on both sides of the ternary Elvis operator.

I'm looking for something like

#{default(obj.property, 'None')}
Nectareous answered 11/9, 2012 at 17:36 Comment(4)
What version of jsf/el as if you are on a new version you can define el functionsMadid
@Stephen: EL functions are always been supported since EL 1.0 and is independent from JSF version.Hillyer
Thanks good to know... Perhaps it is defining them that was tricky until el 2.2Madid
@Stephen: that part was never changed.Hillyer
H
8

No such thing exist in EL. Not now and not in the future.

Your best bet is creating a custom EL function.

#{my:def(obj.property, 'None')}

(note: as default is a Java keyword/literal, it's invalid to use exactly this name as function name in EL)

If you happen to use JSF utility library OmniFaces, then you can use #{of:coalesce()} for the exact purpose.

See also:

Hillyer answered 11/9, 2012 at 19:10 Comment(0)
G
2

In some situations you can use this:

<c:out value="${obj.property}" default="None"/>

(as suggested here)

Grippe answered 19/12, 2014 at 7:47 Comment(2)
OP is using Facelets, not JSP.Hillyer
I did say "in some situations". Also, this is the only question about "replace null with default value in EL" (thet the search provides), so it is what people will find when searching for an answer (related to JSF,JSP or in general).Charla

© 2022 - 2024 — McMap. All rights reserved.