Grails:如何在过滤器中通过controllerName获取控制器?

| 我有一个过滤器和the0ѭvar获取控制器目标。 例如: 当用户尝试访问
/myApp/book/index
时,我的过滤器被触发,
controllerName
等于
book
。如何获得BookController实例? ks 编辑: 我可以用
Artefact
得到:
grailsApplication.getArtefactByLogicalPropertyName(\"Controller\", \"book\")
但是我要如何处理这个伪像?     
已邀请:
        控制器将被注册为spring bean。只需按名称抓取即可:
applicationContext.getBean(\'mypackage.BookController\') // or
def artefact = grailsApplication.getArtefactByLogicalPropertyName(\"Controller\", \"book\")
applicationContext.getBean(artefact.clazz.name)
    
        正如Burt所说,您可能不希望过滤器中有一个控制器实例。这是解决问题的错误方法。 由Spring Framework自动注入的Grails Controllers,在创建时具有一些不可思议的魔力和过程。因此,我可以向您保证,这不是解决此问题的方法。 正如您自己所描述的那样,您想调用您的操作,并且我可以想象您正在尝试重用驻留在您的操作中的某些代码,也许是在数据库中生成某些数据,甚至是与HTTP会话一起使用,我说的对吗 因此,您可以做两件事来解决这种问题。 1)只需将您的请求流重定向到您的控制器/操作,如下所示:
if (something) {
  redirect controller: \'xpto\', action: \'desired\'
  return false
}
2)或者,您可以在操作内部获取逻辑(即执行您要运行的肮脏工作),在一个服务中分离该逻辑,然后按以下方式在两个类(操作/服务)中重用该服务: MyService.groovy
class MyService { 
  def methodToReuse() {
    (...)
  }
}
MyController.groovy
class MyController {

  def myService //auto-injected by the green elf

  def myAction = {
    myService.methodToReuse()
  }
}
MyFilters.groovy
class MyFilters {

  def myService //auto-injected by the red elf

  (...)
  myService.methodToReuse()
  (...)

}
[] s,     
        您应该可以在检索到的文物上呼叫ѭ11。
newInstance
的工作方式与构造函数一样,因此您可以为常规构造函数调用提供任何参数。 因此,您可能可以执行以下操作:
def bookController = grailsApplication.getArtefactByLogicalPropertyName(\"Controller\", \"book\").newInstance()
    
        工作代码:
import org.codehaus.groovy.grails.web.context.ServletContextHolder
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes
import org.springframework.context.ApplicationContext

ApplicationContext applicationContext = (ApplicationContext) ServletContextHolder.getServletContext().getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
def grailsApplication

String nameController = \"search\"
def artefact = grailsApplication.getArtefactByLogicalPropertyName(\"Controller\", nameController)
def controller = applicationContext.getBean(artefact.clazz.name)
    

要回复问题请先登录注册