Grails 控制器渲染方法渲染 vs 响应 [英] Grails controller rendering method render vs respond
问题描述
我刚刚意识到对于 Grails 控制器还有另一种渲染方法响应".
I just realised that for a Grails controller there is another rendering method 'respond'.
如果我们想在控制器中渲染一个视图,respond 和 render 方法有什么区别.
What's the difference between respond and render method if we want to render a view in the controller.
推荐答案
响应方法使用内容协商根据请求的ACCEPT"标头以最合适的内容类型进行响应.
The respond method uses content negotiation to respond with the most appropriate content type based on the requests 'ACCEPT' header.
Accept: text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8, application/json
通过这种方式,您网站的消费者可以选择他们希望返回数据的方式.如果您想强制使用特定的返回类型,这可能不是最佳选择.例如:您正在构建 REST api 并且只想返回 json 或 xml,如果用户要求 test.html 那么他们可能会以您不希望支持的格式返回您的数据.否则,响应可以是一种简单的方法来支持多种返回格式,而无需分别对它们进行编程.
This way the consumer of your site can choose how they wish to be returned data. This may not be the best option if you want to force a specific return type. For example: You are building a REST api and only want to return json or xml, if the user asks for test.html then they may be returned your data in a format that you do not wish to support. Otherwise respond can be an easy way to support multiple return formats without programming them each separately.
Render 明确定义了您希望返回数据的格式:
Render explicitly defines the format you wish to return your data in :
(文档中的示例)
render Book.list(params) as JSON
render Book.get(params.id) as XML
// render with status code
render(status: 503, text: 'Failed to update book ${b.id}')
更多信息:
回复:http://grails.org/doc/latest/ref/Controllers/respond.html渲染:http://grails.org/doc/latest/ref/Controllers/render.html
这篇关于Grails 控制器渲染方法渲染 vs 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!