【问题标题】:How does grails pass arguments to controller methods?Grails 如何将参数传递给控制器​​方法?
【发布时间】:2014-05-07 07:40:43
【问题描述】:

在 grails 控制器示例中,我看到了 save(Model modelInstance) 和 save()。我尝试了他们两个,他们都工作。我想 grails 用参数实例化 modelInstance 。我的假设正确吗?

我还注意到在 index(Integer max) 中,参数是否必须命名为 max?还是任何名称都可以,只要它是一个数字?

这些参数的传递在下面是如何工作的?

【问题讨论】:

  • 您在发帖前阅读过文档吗?这是一个明显的起点 - grails.org/doc/2.1.2/guide/theWebLayer.html#dataBinding
  • 是的,我以前扫描过它们。我只是想知道相同的数据绑定过程是否适用于方法参数。
  • 控制器无法读取您的想法 :) 名称应该相同。也可以通过 params.paramName 访问
  • 当然,在上面链接的“数据绑定和动作参数”一章中有很好的描述。顺便说一句,最好坚持使用官方术语并使用“动作”而不是“控制器方法”——这也不是一回事,因为控制器方法不一定意味着动作。

标签: grails


【解决方案1】:

如果你写一个这样的控制器......

class MyController {
    def actionOne() {
        // your code here
    }

    def actionTwo(int max) {
        // your code here
    }

    def actionThree(SomeCommandObject co) {
        // your code here
    }
}

Grails 编译器会将其转换为类似的内容(不完全是这样,但这有效地描述了正在发生的事情,我认为可以解决您的问题)...

class MyController {
    def actionOne() {
        // Grails adds some code here to
        // do some stuff that the framework needs

        // your code here
    }

    // Grails generates this method...
    def actionTwo() {
        // the parameter doesn't have to be called
        // "max", it could be anything.
        int max = params.int('max')
        actionTwo(max)
    }

    def actionTwo(int max) {
        // Grails adds some code here to
        // do some stuff that the framework needs

        // your code here
    }

    // Grails generates this method...
    def actionThree() {
        def co = new SomeCommandObject()
        bindData co, params
        co.validate()
        actionThree(co)
    }

    def actionThree(SomeCommandObject co) {
        // Grails adds some code here to
        // do some stuff that the framework needs

        // your code here
    }
}

还有其他事情要做,例如强制执行 allowedMethods 检查、强制错误处理等。

希望对你有帮助。

【讨论】:

  • 很好的答案!谢谢:)
猜你喜欢
  • 1970-01-01
  • 2012-12-04
  • 1970-01-01
  • 2020-05-19
  • 2014-07-21
  • 2011-09-02
  • 2015-01-25
  • 1970-01-01
  • 2018-07-14
相关资源
最近更新 更多