simple groovy operator question: Math.min(params.max ? params.int('max') : 10, 100)
Can you tel开发者_运维知识库l me how the expression
Math.min(params.max ? params.int('max') : 10, 100)
works? It doesn't fit the groovy ternary if, so what special operator is this?
Thanks
Is it clear now?
def max = params.max? params.int('max') : 10
Math.min(max, 100)
BTW this is a nice idiom popular in Grails - if the parameter max
exists, read it, but if it exceeds given value (100
by default), truncate it to 100
. This way an attacker or malignant user won't make your application to return arbitrary big amount of data from the database.
Perhaps breaking it up into two expressions would help. params.max ? params.int('max') : 10
is the ternary expression...the result of which ends up being the first arg to Math.min
(with 100
being the other arg).
Looks like the end result is an integer that's limited to being at most 100, and defaults to 10.
When protecting against attack, you may want to look at the bottom bounds as well. I just ran across this in grails 2.4.4: Anything less than 1 appears to return all records. It's not documented, and the source appears to check for values > -1, but I found I had to check values > 0:
//Use value, if found, else 20
int max = params.getInt('max') ?: 20
//no less than 1, no more than 100: max < 1 returns ALL records (grails 2.4.4)
max = Math.max(max, 1)
max = Math.min(max, 100)
Domain.list(max: max)
精彩评论