首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >读出Grails-Controller中的所有操作

读出Grails-Controller中的所有操作
EN

Stack Overflow用户
提问于 2010-06-02 17:11:08
回答 5查看 5.2K关注 0票数 6

我需要从我的web应用中的任何控制器中读出所有可用的操作。这样做的原因是一个授权系统,我需要给用户一个允许的操作列表。

例如:用户xyz拥有执行显示、列表、搜索等操作的权限。用户admin具有执行编辑、删除等操作的权限。

我需要从控制器中读出所有动作。有谁有主意吗?

EN

回答 5

Stack Overflow用户

发布于 2010-06-02 23:17:16

这将创建一个包含控制器信息的Map列表( 'data‘变量)。

代码语言:javascript
复制
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
}
票数 9
EN

Stack Overflow用户

发布于 2013-05-22 23:48:44

下面是一个使用Grails 2的示例,即它将捕获定义为方法或闭包的操作

代码语言:javascript
复制
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
            }
        }
    }
}
票数 6
EN

Stack Overflow用户

发布于 2012-05-23 00:33:38

Grails不支持一种直接的方法来实现这一点。然而,我能够从可用的grails方法中拼凑出一个难题,并得出以下解决方案:

代码语言:javascript
复制
def actions = new HashSet<String>()
def controllerClass = grailsApplication.getArtefactInfo(ControllerArtefactHandler.TYPE)
                         .getGrailsClassByLogicalPropertyName(controllerName)
for (String uri : controllerClass.uris ) {
    actions.add(controllerClass.getMethodActionName(uri) )
}

变量grailsApplication和controllerName是由grails注入的。由于控制器本身没有必要的方法,下面的代码检索它的controllerClass (请参阅GrailsControllerClass),其中包含我们需要的东西:属性uris和方法getMethodActionName

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2956294

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档