4

If would be great if I could replace

${myvar eq 'foo' or myvar eq 'bar' or myvar eq 'john' or myvar eq 'doe' or myvar eq ...}

by either

${myvar in ['foo', 'bar', 'john', 'doe', ...]}

or

${myvar in {'foo', 'bar', 'john', 'doe', ...}}

but none of them worked. Any alternative solution?

sp00m
  • 47,968
  • 31
  • 142
  • 252

2 Answers2

4

First create an EL function for that. A kickoff example for Facelets can be found in this answer and another one for JSP can be found somewhere near the bottom of our EL wiki page.

public static boolean contains(Object[] array, Object item) {
    if (array == null || item == null) {
        return false;
    }

    for (Object object : array) {
        if (object != null && object.toString().equals(item.toString())) {
            return true;
        }
    }

    return false;
}

(or if you're using JSF utility library OmniFaces, use its of:contains(), although it works in Facelets only, not in the deprecated JSP)

then use it as follows:

<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@taglib prefix="my" uri="http://my.example.com/functions" %>
...
${my:contains(fn:split('foo,bar,john,doe', ','), myvar)}

(the fn:split() is merely a trick to convert a delimited String to a String[])

You could even simplify/specialize it further by passing the delimited string directly and perform the split in the function so that you can end up like as:

${my:contains('foo,bar,john,doe', myvar)}
Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
2

Define a variable mylist with the list of names and use contains:

mylist.contains(myvar)
Óscar López
  • 232,561
  • 37
  • 312
  • 386