Grails控制器渲染方法呈现vs响应 [英] Grails controller rendering method render vs respond

查看:90
本文介绍了Grails控制器渲染方法呈现vs响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



响应之间的区别是什么? > render 方法,如果我们想在控制器中呈现视图。

解决方案

响应方法使用内容协商

 接受:text / html,application / xhtml + xml,application / xml; q = 0.9,* / *; q = 0.8,application / json 

这样,您的网站的消费者可以选择他们希望如何返回数据。如果你想强制一个特定的返回类型,这可能不是最好的选择。例如:您正在构建REST api,并且只想返回json或xml,如果用户请求test.html,那么它们可能会以您不希望支持的格式返回数据。否则,响应可以是一种简单的方法来支持多种返回格式,而无需分别编程它们。



渲染明确定义了您希望返回数据的格式:

p>

 将Book.list(params)渲染为JSON 
将Book.get(params.id)渲染为XML

//呈现状态码
render(status:503,text:'未能更新book $ {b.id}')

更多信息:

回应:http://grails.org/doc/latest/ref/Controllers/respond.html
渲染: http://grails.org/doc/latest/ref/Controllers/render.html


I just realised that for a Grails controller there is another rendering method 'respond'.

What's the difference between respond and render method if we want to render a view in the controller.

解决方案

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

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 explicitly defines the format you wish to return your data in :

(Examples from documentation)

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

More information:

Respond: http://grails.org/doc/latest/ref/Controllers/respond.html Render:http://grails.org/doc/latest/ref/Controllers/render.html

这篇关于Grails控制器渲染方法呈现vs响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆