grails - 有没有更简单的方法可以在Grails中进行内容协商的响应?

标签 grails controller content-negotiation

根据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 }
        }
    }
}

但是,我希望所有 Controller 方法的响应都可以做到这一点。除了在每个返回内容的操作末尾简单地复制粘贴withFormat块之外,还有一种更好的方法来获得这种行为?

最佳答案

突然出现在我脑海的两件事是拦截器和过滤器:

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。 Bummer,因为这更具全局化性。

过滤器将在每个 Controller 的每个 Controller 上运行,但是至少您要在该级别上将重复量最小化。

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

旋转一下,让我知道您的想法。

关于grails - 有没有更简单的方法可以在Grails中进行内容协商的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8523820/

相关文章:

grails - 如何将Javassist实例转换为特定域的实例

php - 消除 Zend Framework Controller 文件名中对 "controller"的需要

grails - Gant构建脚本,如何检索我要执行的任务

grails - 在PeriodSelector AMChart中发送Ajax请求

unit-testing - 使用 IVY 解析器进行 Grails 2.3 单元测试

ruby-on-rails - 使用 Ruby on Rails 将 XHTML 作为 application/xhtml+xml 提供服务

java - Spring API 中是否有更好的基于 Accept Header 的内容协商方法?

java - LWJGL 中不是游戏 handle 的 Controller

list - Grails Controller : access to parameter that has a list of elements

ajax - 使用浏览器后退按钮时忽略内容协商