Adam
Adam

Reputation: 3013

Guard against null in spring expression

I have the following in a jsp page, where bar is a field (which can be null) of foo

<c:set var="fieldAccessorsSuppliedToComponent" value="foo.bar.name" />

//omissions

<spring:eval expression="${fieldAccessorsSuppliedToComponent}" var="currentField"/>

I have no control over what fieldAccessorsSuppliedToComponent is going to be, foo.bar1.bar2.bar3.address.city is possible and any step could be null. I have currently solved it by looping over 'fields' ->

<c:set var="fields" value="${fn:split(column, '.')}" />

and testing each step for null. Its a mess. Can it be done with something inbuilt in SPeL

What is the simplest way to make it work with nulls? Silently failing and not setting currentField is ideal.

Upvotes: 0

Views: 201

Answers (1)

Artem Bilan
Artem Bilan

Reputation: 121590

where bar is a field (which can be null) of foo

The Null-safer Navigator operator comes to the rescue:

value="foo.bar?.name"

See more info in the documentation: https://docs.spring.io/spring/docs/5.2.4.RELEASE/spring-framework-reference/core.html#expressions-operator-safe-navigation

Upvotes: 1

Related Questions