Expression language: how to simplify this operator (required "in" -like article)

If it 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 ...} 

or

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

or

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

but none of them worked. Any alternative solution?

+4
source share
2 answers

First create an EL function for this. An example run for Facelets can be found in this answer , and another for JSP can be found somewhere at the bottom of our EL wiki .

 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 use the OmniFaces JSF utility library, use of:contains() , although it only works in Facelets and not in legacy 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)} 

( fn:split() is just a trick for converting the String separator to String[] )

You can even simplify / specialize it by passing the delimited string directly and do the function splitting so you can end up like this:

 ${my:contains('foo,bar,john,doe', myvar)} 
+4
source

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

 mylist.contains(myvar) 
+2
source

All Articles