Grails controllers repeated code for all actions

2019-05-26 08:20发布

问题:

Imagine this controller:

class exampleController{

def action1 = {}

def action2 = {}

def action3 = {}

def action4 = {}

def action5 = {}

}

I want to be able to return in all the action in this controller the same params. Imagining this:

def user = session.user    
[user: user]

Is there any way of doing this, besides writing all the same code on all the actions? The session.user return params is just an example. I don't wanna really return it.

回答1:

A simple solution is to put this code in a method and call it from each action

class exampleController{

  def action1 = {getModel()}

  def action2 = {getModel()}

  def action3 = {getModel()}

  def action4 = {getModel()}

  def action5 = {getModel()}

  private getModel() {
    def user = session.user    
    [user: user]    
  }
}

While this does involve some amount of repetition (invocation of the same method), it's a lot more obvious what's happening here. When debugging/testing a controller it's easy to forget about filters and interceptors, which can often lead to questions like

what the @**% is going on here?



回答2:

Use a filter - http://grails.org/doc/latest/guide/6.%20The%20Web%20Layer.html#6.6%20Filters - or an after interceptor - http://grails.org/doc/latest/guide/6.%20The%20Web%20Layer.html#6.1.5%20Controller%20Interceptors



回答3:

I have a similar case, and I was modified the grails scaffolding for the controller's generator.

class MyClassController {

    def list = {
        ...
    }

    def show = {
        def eInstance = beanIfExist()
        ...
    }

    def edit = {
        def eInstance = beanIfExist()
        ...
    }

    def update = {
        def eInstance = beanIfExist()
        ...
    }

    def delete = {
        def eInstance = beanIfExist()
        ...
    }

    def beanIfExist = {
        def beanInstance = MyClass.get(params.id)
        if (beanInstance) {
            return beanInstance
        } else {
            flash.message = "Error, invalid record."
            redirect(action: "list")
            return null
        }
    }

}

It is my suggestion, now if do you need another that sent a data to view then you can use interceptors.