grails response、render、redirect的区别

本文介绍了如何使用response、render和redirect来处理HTTP响应。通过response可以根据客户端请求的数据格式发送响应;render用于界面跳转并输出数据,支持多种数据格式;redirect则实现URL重定向。文章还提供了多个示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.response

基于request的‘ACCEPT’header来协商响应数据的格式 。reponse之后,程序会继续执行,后面可以使用render、redirect,但response无作用。 

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

2.render

界面跳转(url不变)、向网页输出数据。明确的指定返回数据的格式 。render之后,程序会继续执行,但是后面不能使用redirect、response。

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

例子:

 

// renders text to response
render "some text"

// renders text for a specified content-type/encoding
render(text: "<xml>some xml</xml>", contentType: "text/xml", encoding: "UTF-8")

// render a template to the response for the specified model
def theShining = new Book(title: 'The Shining', author: 'Stephen King')
render(template: "book", model: [book: theShining])

// render each item in the collection using the specified template
render(template: "book", collection: [b1, b2, b3])

// render a template to the response for the specified bean
def theShining = new Book(title: 'The Shining', author: 'Stephen King')
render(template: "book", bean: theShining)

// render the view with the specified model
def theShining = new Book(title: 'The Shining', author: 'Stephen King')
render(view: "viewName", model: [book: theShining])

// render the view with the controller as the model
render(view: "viewName")

// render some markup to the response
render {
    div(id: "myDiv", "some text inside the div")
}

// render some XML markup to the response
render(contentType: "text/xml") {
    books {
         for (b in books) {
             book(title: b.title, author: b.author)
         }
    }
}

// render a JSON ( http://www.json.org ) response with the builder attribute:
render(contentType: "application/json") {
    book(title: b.title, author: b.author)
}

// render with status code
render(status: 503, text: 'Failed to update book ${b.id}')

// render a file
render(file: new File(absolutePath), fileName: "book.pdf")

 

redirect

重定向,url会改变。

 

最后欢迎大家访问我的个人网站:1024s​​​​​​​

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值