Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails: how to get a controller by controllerName in a filter?

Tags:

filter

grails

I have a filter and the controllerName var getting controller target.

For example: when user try to access /myApp/book/index, my filter is triggered and controllerName is equals book. How can I get a BookController instance?

Tks


EDIT:

I can get an Artefact using:

grailsApplication.getArtefactByLogicalPropertyName("Controller", "book")

But what I do with this artefact?

like image 733
Topera Avatar asked Nov 29 '22 10:11

Topera


2 Answers

The controller will be registered as a spring bean. Just grab it by name:

applicationContext.getBean('mypackage.BookController') // or
def artefact = grailsApplication.getArtefactByLogicalPropertyName("Controller", "book")
applicationContext.getBean(artefact.clazz.name)
like image 89
ataylor Avatar answered Dec 04 '22 02:12

ataylor


As Burt said, you probably don't want one controller instance inside your filter. This is a wrong way to solve your problem.

Grails Controllers as injected automagically by Spring Framework, and there is some black magic and procedures made when creating it. So, I can assure you this is not the way to solve this problem.

As you yourself described, you want to call your action, and I can imagine you're trying to reuse some code that resides in your action, maybe to generate some data in your database, or even to work with your HTTP session, am I right?

So, you can do two things to solve this kind of issue.

1) Just redirect your request flow to to your controller/action like this:

if (something) {
  redirect controller: 'xpto', action: 'desired'
  return false
}

2) Or you can get the logic inside your action (that is doing that dirty job you want to run), separate that logic inside one service, and reuse the service in both classes (action / service) this way:

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,

like image 25
Lucas Teixeira Avatar answered Dec 04 '22 03:12

Lucas Teixeira