6.1.12 简单类型转换器 - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith
Version: null
6.1.12 简单类型转换器
Type Conversion Methods
If you prefer to avoid the overhead of Data Binding and simply want to convert incoming parameters (typically Strings) into another more appropriate type the params object has a number of convenience methods for each type:def total = params.int('total')int method, and there are also methods for boolean, long, char, short and so on. Each of these methods is null-safe and safe from any parsing errors, so you don't have to perform any additional checks on the parameters.Each of the conversion methods allows a default value to be passed as an optional second argument. The default value will be returned if a corresponding entry cannot be found in the map or if an error occurs during the conversion. Example:def total = params.int('total', 42)attrs parameter of GSP tags.
类型转换方法
如果你倾向于避免数据绑定的开销,而只想简单地将输入参数(通常是字符串)转换为另外更合适地类型,可以通过params对象提供的一些便利方法来实现:def total = params.int('total')int方法,除此之外还有boolean、long、char、short等方法。每一个方法都是空指针安全的(null-safe)和类型解析安全的,因此你也就不需要执行任何额外的参数检查了。每一个转换方法都允许将一个缺省值传递给第二个可选参数。如果映射中没有找到对应的实体或者进行转换的时候出现了错误,此缺省值将被返回。比如:def total = params.int('total', 42)attrs参数。Handling Multi Parameters
A common use case is dealing with multiple request parameters of the same name. For example you could get a query string such as?name=Bob&name=Judy.In this case dealing with one parameter and dealing with many has different semantics since Groovy's iteration mechanics for String iterate over each character. To avoid this problem the params object provides a list method that always returns a list:for (name in params.list('name')) {
println name
}处理多个重名参数
我们会经常碰到要处理多个请求参数名相同的情况。比如得到你得到一个内容是?name=Bob&name=Judy的查询串这种情况下,处理一个参数和多个参数的语法是有些不同的,因为Groovy的String迭代是基于字符的。要避免此问题,可以使用params对象提供的list方法,此方法总是返回一个列表:for (name in params.list('name')) {
println name
}
