【问题标题】:Is there an easier way to do content negotiated responses in Grails?有没有更简单的方法在 Grails 中进行内容协商响应?
【发布时间】:2011-12-15 17:01:20
【问题描述】:

根据 Grails 用户指南中的内容,recommended way 根据内容协商发送不同的内容格式是使用 withFormat 块:

import grails.converters.XML
class BookController {

    def list() {
        def books = Book.list()
        withFormat {
            html bookList: books
            js { render "alert('hello')" }
            xml { render books as XML }
        }
    }
}

但是,我希望我的所有控制器方法的响应都能做到这一点。有没有比在每个内容返回操作结束时简单地复制粘贴 withFormat 块更好的方法来获得这种行为?

【问题讨论】:

    标签: grails controller content-negotiation


    【解决方案1】:

    首先出现在我脑海中的两件事是拦截器和过滤器:

    http://grails.org/doc/1.3.7/ref/Controllers/afterInterceptor.html

    http://grails.org/doc/latest/guide/6.%20The%20Web%20Layer.html#6.6 过滤器

    拦截器不起作用,因为您不能使用 withFormat。太糟糕了,因为这是一个更加全球化的环境。

    过滤器将在每个控制器的基础上工作,但至少您会在该级别上最大限度地减少重复。

    def afterInterceptor = {model, modelAndView ->
        withFormat {
            html { model }
            js { render "alert('hello')" }
            xml { render model as XML }
        }
    }
    

    这在我的测试项目中对我有用。我尝试将这个闭包放入它自己的类中并在类中混合,这样你就可以做一个更全局的解决方案......不过没有骰子。

    也许你所有的 afterInterseptors 都将模型 modelAndView 传递给一个公共类?这似乎有效:)(在回答时努力寻找答案)

    @Mixin(AfterInterceptorWithFormat)
    class FirstController {
    
        def action1 = {}
        def action2 = {}
    
        def afterInterceptor = {model, modelAndView ->
            performAfterInterceptor(model, modelAndView)
        }
    }
    
    class AfterInterceptorWithFormat {
    
        def performAfterInterceptor(model, modelAndView) {
            withFormat {
                html { model }
                js { render "alert('hello')" }
                xml { render model as XML }
            }
        }
    }
    

    试一试,让我知道你的想法。

    【讨论】:

      【解决方案2】:

      我最终做的是简单地调整默认的 CRUD 模板,在每个方法的末尾添加 withFormat 块。

      我意识到我真正想要的只是内容协商的 CRUD,因此我只需要将代码放入模板中。

      我的应用程序的非 crud 部分的其余控制器不需要 no-html 输出,因此我不需要对除 crud 控制器之外的任何内容进行内容协商。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-25
        • 1970-01-01
        • 1970-01-01
        • 2023-02-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多