【问题标题】:Grails controllers repeated code for all actionsGrails 控制器为所有操作重复代码
【发布时间】:2011-09-10 06:24:34
【问题描述】:

想象一下这个控制器:

class exampleController{

def action1 = {}

def action2 = {}

def action3 = {}

def action4 = {}

def action5 = {}

}

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

def user = session.user    
[user: user]

除了在所有动作上编写所有相同的代码之外,还有什么方法可以做到这一点? session.user 返回参数只是一个例子。我真的不想退货。

【问题讨论】:

    标签: grails controller action


    【解决方案1】:

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

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

    虽然这确实涉及一些重复(调用相同的方法),但这里发生的事情要明显得多。在调试/测试控制器时,很容易忘记过滤器和拦截器,这通常会导致诸如

    之类的问题

    @**% 是怎么回事?

    【讨论】:

      【解决方案2】:
      【解决方案3】:

      我有一个类似的案例,我为控制器的生成器修改了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
              }
          }
      
      }
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多