Reading out all actions in a Grails-Controller

前端 未结 5 575
别跟我提以往
别跟我提以往 2021-01-02 20:53

I need to read out all available actions from any controller in my web-app. The reason for this is an authorization system where I need to give users a list of allowed actio

5条回答
  •  一向
    一向 (楼主)
    2021-01-02 21:33

    Here's an example that works with Grails 2, i.e it will capture actions defined as either methods or closures

    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
                }
            }
        }
    }
    

提交回复
热议问题