how to check if a parameter exists in params?
for ( boldParam in [para1, para2, para2, para4, para5] ) {
if(/* boldPa开发者_如何学编程ram exists in params */)
ilike(boldParam,'%' + params.boldParam + '%')
}
}
I would like to write something like above. I'm trying to avoid the following multiple if statements:
if (params.para1)
ilike('para1','%' + params.para1+ '%')
if (params.para2)
ilike('para2','%' +params.para2+ '%')
if (params.para3)
ilike('para3','%' + params.para3+ '%')
params
is a Map
, so you can use containsKey()
:
for (boldParam in [para1, para2, para2, para4, para5]) {
if (params.containsKey(boldParam)) {
ilike(boldParam, '%' + params.boldParam + '%')
}
}
Trying to retrieve property that does not exist will give you null
. That means you can simply do
if (!params.missing) {
println("missing parameter is not present within request.")
}
In different use case you could also give a try to safe dereference operator ?.
. For example:
params.email?.encodeAsHTML()
An alternative used by me:
['param1','param2','param3','param4','param5'] /* and it also could come from a service */
.each {
if (params["${it}"]) filters["${it}"] = params["${it}"]
} /* Do it in your controller and then send $filters to your service */
精彩评论