Some tutorials on the internet recommend setting a variable $Integer to the constant of 0 and then calling parseInt method on it like this:
Code Block | ||||
---|---|---|---|---|
| ||||
#set ($Integer = 0) #if ($parameters.get("ItemsPerPage")) #set ($ItemsPerPage = $Integer.parseInt($parameters.get("ItemsPerPage"))) #else #set ($ItemsPerPage = 6) #end |
The problem is that $Integer.parseInt won't handle bad input gracefully. Instead the proper way to code this type of logic is:
Code Block | ||||
---|---|---|---|---|
| ||||
#set ($ItemsPerPage = 6) #if ($formatHelper.parseInteger($parameters.get("ItemsPerPage"))) #set ($ItemsPerPage = $formatHelper.parseInteger($parameters.get("ItemsPerPage"))) #if ($ItemPerPage < 1 || $ItemPerPage > 50) #set ($ItemsPerPage = 6) #end #end |
Notice that we default to 6, if the parameter is parsable then we'll assign it's parsed value to the ItemsPerPage variable. $Integer.parseIntWe then sanity check the range of the value to make sure it's reasonable.