如要在所有的Controller中使用transport2Map方法
在BootStarp的类如下
import org.codehaus.groovy.grails.commons.GrailsApplication
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes
import org.springframework.context.ApplicationContext
class BootStrap {
def init = { servletContext ->
ApplicationContext applicationContext = servletContext.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
GrailsApplication application = (GrailsApplication) applicationContext.getBean("grailsApplication")
addDynamicMethods(applicationContext, application)
}
def destroy = {
}
def addDynamicMethods = { ApplicationContext applicationContext, GrailsApplication application ->
addDynamicControllerMethods(applicationContext, application)
}
def addDynamicControllerMethods = { ApplicationContext applicationContext, GrailsApplication application ->
application.controllerClasses.each { controllerClass ->
controllerClass.metaClass."transport2Map" = { obj -> //将页面中数组对像转成Map
Map split = obj?.inject([:]) { map, param -> //页面参数的格式如:user.1-name
List list = param.key.split('-')
if (list.size() != 2) { // only allow for 1 '-' in a param
return map
}
String firstKey = list.first()
String lastKey = list.last()
if (!map.get(firstKey)) {
map."$firstKey" = [:] // init map for this key
}
map."$firstKey"."$lastKey" = param.value
return map
}
}
}
}
}
在BootStarp的类如下
import org.codehaus.groovy.grails.commons.GrailsApplication
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes
import org.springframework.context.ApplicationContext
class BootStrap {
def init = { servletContext ->
ApplicationContext applicationContext = servletContext.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
GrailsApplication application = (GrailsApplication) applicationContext.getBean("grailsApplication")
addDynamicMethods(applicationContext, application)
}
def destroy = {
}
def addDynamicMethods = { ApplicationContext applicationContext, GrailsApplication application ->
addDynamicControllerMethods(applicationContext, application)
}
def addDynamicControllerMethods = { ApplicationContext applicationContext, GrailsApplication application ->
application.controllerClasses.each { controllerClass ->
controllerClass.metaClass."transport2Map" = { obj -> //将页面中数组对像转成Map
Map split = obj?.inject([:]) { map, param -> //页面参数的格式如:user.1-name
List list = param.key.split('-')
if (list.size() != 2) { // only allow for 1 '-' in a param
return map
}
String firstKey = list.first()
String lastKey = list.last()
if (!map.get(firstKey)) {
map."$firstKey" = [:] // init map for this key
}
map."$firstKey"."$lastKey" = param.value
return map
}
}
}
}
}