gpt4 book ai didi

grails - 替换invokeMethod来拦截Controller方法

转载 作者:行者123 更新时间:2023-12-02 15:28:13 24 4
gpt4 key购买 nike

我想通过替换ExpandoMetaClass的invokeMethod关闭来拦截所有 Controller 中的所有方法。

我创建了一个新的grails项目(2.3.5)。创建了一个新的 Controller ,称为AccountController:

package com.invoke.test
class AccountController {
def index() {
System.out.println("Index Called")
}
}

然后创建另一个名为SecurityBootStrap的BootStrap:
class SecurityBootStrap {

def grailsApplication

def verifyMethodAccess = { String name, args ->
log.info "Called method ${name}"
def method = delegate.metaClass.getMetaMethod(name, args)
if (method) {
return method.invoke(delegate, args)
}
return null
}

def init = { servletContext ->
grailsApplication.controllerClasses.each { controllerClass ->
controllerClass.clazz.metaClass.invokeMethod = verifyMethodAccess
log.info "Replaced the invokeMethod closure on ${controllerClass.clazz}"
}
}
}

启动该应用程序后,该日志看起来很有希望:
|Running Grails application
2014-06-26 15:07:26,476 [localhost-startStop-1] INFO conf.SecurityBootStrap - Replaced the invokeMethod closure on class grails.plugin.databasemigration.DbdocController
2014-06-26 15:07:26,477 [localhost-startStop-1] INFO conf.SecurityBootStrap - Replaced the invokeMethod closure on class com.invoke.test.AccountController
|Server running. Browse to http://localhost:8080/InvokeTest

但是,当调用 http://localhost:8080/InvokeTest/account/index时,日志如下所示:
Index Called

我期望它是:
Called method index
Index Called

提前致谢

最佳答案

您可以使用编译时元编程来做到这一点,但是不能使用运行时元编程来做到这一点。 Groovy运行时元编程的局限性在于它仅适用于从Groovy启动的方法调用。许多Grails框架都是用Java编写的。

例:

class Widget {
def getTheAnswer() {
42
}
}

Widget.metaClass.getTheAnswer = { ->
2112
}

当Groovy代码调用 new Widget().getTheAnswer()时,结果将为2112。当Java代码调用 new Widget().getTheAnswer();时,结果将为42。

关于grails - 替换invokeMethod来拦截Controller方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24431859/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com