读出Grails-Controller中的所有操作

ken*_*nan 6 grails grails-controller

我需要从我的网络应用程序中的任何控制器中读出所有可用的操作.这样做的原因是授权系统,我需要向用户提供允许的操作列表.

例如:用户xyz具有执行动作节目,列表,搜索的授权.用户admin具有执行操作编辑,删除等操作的权限.

我需要从控制器中读出所有动作.有没有人有想法?

Bur*_*ith 9

这将创建一个带有控制器信息的地图列表('数据'变量).List中的每个元素都是一个带有键'controller'的Map,对应于控制器的URL名称(例如BookController - >'book'),对应于类名的controllerName('BookController')和对应的'actions' a该控制器的操作名称列表:

import org.springframework.beans.BeanWrapper
import org.springframework.beans.PropertyAccessorFactory

def data = []
for (controller in grailsApplication.controllerClasses) {
    def controllerInfo = [:]
    controllerInfo.controller = controller.logicalPropertyName
    controllerInfo.controllerName = controller.fullName
    List actions = []
    BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(controller.newInstance())
    for (pd in beanWrapper.propertyDescriptors) {
        String closureClassName = controller.getPropertyOrStaticPropertyOrFieldValue(pd.name, Closure)?.class?.name
        if (closureClassName) actions << pd.name
    }
    controllerInfo.actions = actions.sort()
    data << controllerInfo
}
Run Code Online (Sandbox Code Playgroud)

  • 仍然支持闭包,但首选方法.我可以使用@ grails.web.Action注释搜索方法 (3认同)

Dón*_*nal 6

这是与Grails 2配合使用的示例,即它将捕获定义为方法或闭包的动作

import org.codehaus.groovy.grails.commons.DefaultGrailsControllerClass
import java.lang.reflect.Method
import grails.web.Action

// keys are logical controller names, values are list of action names  
// that belong to that controller
def controllerActionNames = [:]

grailsApplication.controllerClasses.each { DefaultGrailsControllerClass controller ->

    Class controllerClass = controller.clazz

    // skip controllers in plugins
    if (controllerClass.name.startsWith('com.mycompany')) {
        String logicalControllerName = controller.logicalPropertyName

        // get the actions defined as methods (Grails 2)
        controllerClass.methods.each { Method method ->

            if (method.getAnnotation(Action)) {
                def actions = controllerActionNames[logicalControllerName] ?: []
                actions << method.name

                controllerActionNames[logicalControllerName] = actions
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)