2011-06-07 134 views
2

想象一下这样的控制器:Grails的控制器重复的代码为所有操作

class exampleController{ 

def action1 = {} 

def action2 = {} 

def action3 = {} 

def action4 = {} 

def action5 = {} 

} 

我希望能够在所有的行动来回报这个控制器相同PARAMS。想象一下:

def user = session.user  
[user: user] 

除了在所有操作上写出所有相同的代码之外,是否有这样做的方法? session.user返回参数只是一个例子。我不想真的回报它。

回答

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

虽然这并涉及一些量的重复(调用相同的方法),这里发生了什么更明显。在调试/测试控制器时,很容易忘记过滤器和拦截器,这通常会导致如下问题:

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

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

} 

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

相关问题