gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:46:36 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com