Reading out all actions in a Grails-Controller

前端 未结 5 586
别跟我提以往
别跟我提以往 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:41

    This will create a List of Maps (the 'data' variable) with controller information. Each element in the List is a Map with keys 'controller', corresponding to the URL name of the controller (e.g. BookController -> 'book'), controllerName corresponding to the class name ('BookController'), and 'actions' corresponding to a List of action names for that controller:

    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
    }
    

提交回复
热议问题