Grails控制器重复所有操作的代码

时间:2011-06-07 17:02:02

标签: grails controller action

想象一下这个控制器:

class exampleController{

def action1 = {}

def action2 = {}

def action3 = {}

def action4 = {}

def action5 = {}

}

我希望能够在此控制器的所有动作中返回相同的参数。想象一下:

def user = session.user    
[user: user]

除了在所有动作上编写所有相同的代码之外,还有什么方法可以做到这一点吗? session.user return params就是一个例子。我不想真的回归它。

3 个答案:

答案 0 :(得分:5)

一个简单的解决方案是将此代码放入方法中并从每个操作中调用它

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]    
  }
}

虽然这确实涉及一定程度的重复(调用相同的方法),但更明显的是这里发生了什么。在调试/测试控制器时,很容易忘记过滤器和拦截器,这往往会导致像

这样的问题
  

@ **%在这里发生了什么?

答案 1 :(得分:3)

答案 2 :(得分:0)

我有一个类似的案例,我修改了控制器生成器的grails脚手架。

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
        }
    }

}

这是我的建议,现在如果您需要另一个发送数据进行查看,那么您可以使用拦截器。

相关问题