我需要从我的web应用中的任何控制器中读出所有可用的操作。这样做的原因是一个授权系统,我需要给用户一个允许的操作列表。
例如:用户xyz拥有执行显示、列表、搜索等操作的权限。用户admin具有执行编辑、删除等操作的权限。
我需要从控制器中读出所有动作。有谁有主意吗?
发布于 2010-06-02 23:17:16
这将创建一个包含控制器信息的Map列表( 'data‘变量)。
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
}发布于 2013-05-22 23:48:44
下面是一个使用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
}
}
}
}发布于 2012-05-23 00:33:38
Grails不支持一种直接的方法来实现这一点。然而,我能够从可用的grails方法中拼凑出一个难题,并得出以下解决方案:
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
https://stackoverflow.com/questions/2956294
复制相似问题