【问题标题】:Grails redirect breaks params typesGrails 重定向中断参数类型
【发布时间】:2011-11-05 02:28:48
【问题描述】:

我的 Grails 代码有一个搜索功能,可以在执行 findAllBy 查询后重定向到另一个控制器操作:

def results = Foo.findAllByBar(baz)
redirect(action: "result", params: [results: results])

findAllByBar 返回一个带有模型的 ArrayList,正如预期的那样,但是在重定向之后,接收操作会得到一个 String 数组。更糟糕的是,当只有一个结果时,它甚至没有得到一个数组,它只是得到一个字符串。

鉴于我必须在接收视图中遍历结果,在字符串上执行此操作将仔细地单独打印每个字母。我们都同意这可能不是理想的行为。

【问题讨论】:

    标签: grails grails-controller


    【解决方案1】:

    重定向会产生一个带有查询字符串中参数的新 GET 请求,例如/controller/result?foo=bar&baz=123 - 你不能把对象放在那里,因为它只是一个字符串。

    您可以将对象的 id 放在参数中并在 result 操作中加载它们:

    def action1 = {
       def results = Foo.findAllByBar(baz)
       redirect(action: "result", params: [resultIds: results.id.join(',')])
    }
    
    def result = {
       def resultIds = params.resultIds.split(',')*.toLong()
       def results = Foo.getAll(resultIds)
    }
    

    或将它们放在 Flash 范围内:

    def action1 = {
       flash.results = Foo.findAllByBar(baz)
       redirect(action: "result")
    }
    
    def result = {
       def results = flash.results
    }
    

    【讨论】:

    • 这是有道理的——我假设同一个控制器内的重定向是在同一个请求中委托的。
    • 为此使用forward
    【解决方案2】:

    听起来您想使用链方法而不是重定向方法。 Chain 允许您将模型作为类似于渲染的参数传递。 一个例子是:

    chain(action:'result',model:[results:results])
    

    这里是更多信息的链接: http://www.grails.org/doc/latest/ref/Controllers/chain.html

    【讨论】:

    • 不错...不知道chain。使用它有什么缺点吗?与重定向?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-01
    • 2012-09-08
    相关资源
    最近更新 更多