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

Top*_*era 4 grails filter

我有一个过滤器和controllerNamevar获取控制器目标.

例如:当用户尝试访问时/myApp/book/index,我的过滤器被触发并且controllerName等于book.如何获得BookController实例?

TKS


编辑:

我可以得到一个Artefact使用:

grailsApplication.getArtefactByLogicalPropertyName("Controller", "book")
Run Code Online (Sandbox Code Playgroud)

但是我对这件艺术品做了什么呢?

ata*_*lor 15

控制器将注册为spring bean.只需按名称抓住它:

applicationContext.getBean('mypackage.BookController') // or
def artefact = grailsApplication.getArtefactByLogicalPropertyName("Controller", "book")
applicationContext.getBean(artefact.clazz.name)
Run Code Online (Sandbox Code Playgroud)


小智 5

正如Burt所说,您可能不希望过滤器中有一个控制器实例.这是解决问题的错误方法.

Grails控制器由Spring Framework自动注入,并且在创建它时会产生一些黑魔法和程序.所以,我可以向你保证,这不是解决这个问题的方法.

正如您自己所描述的,您想要调用您的操作,我可以想象您正在尝试重用一些驻留在您的操作中的代码,可能在您的数据库中生成一些数据,甚至可以使用您的HTTP会话,我是对?

所以,你可以做两件事来解决这类问题.

1)只需将您的请求流重定向到您的控制器/操作,如下所示:

if (something) {
  redirect controller: 'xpto', action: 'desired'
  return false
}
Run Code Online (Sandbox Code Playgroud)

2)或者您可以获取操作中的逻辑(即执行您想要运行的脏任务),在一个服务中分离该逻辑,并以这种方式重用两个类(操作/服务)中的服务:

MyService.groovy

class MyService { 
  def methodToReuse() {
    (...)
  }
}
Run Code Online (Sandbox Code Playgroud)

MyController.groovy

class MyController {

  def myService //auto-injected by the green elf

  def myAction = {
    myService.methodToReuse()
  }
}
Run Code Online (Sandbox Code Playgroud)

MyFilters.groovy

class MyFilters {

  def myService //auto-injected by the red elf

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

}
Run Code Online (Sandbox Code Playgroud)

[] S,