Grails控制器重复了所有操作的代码 [英] Grails controllers repeated code for all actions

查看:154
本文介绍了Grails控制器重复了所有操作的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象这个控制器:

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]

有没有办法这样做,除了在所有的操作上编写所有相同的代码? session.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.

推荐答案

一个简单的解决方案是将这个代码放在一个方法中,并从每个action

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?

这篇关于Grails控制器重复了所有操作的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆