Controller - respond

Summary

  • 官方文档:http://docs.grails.org/latest/ref/Controllers/respond.html
  • 为当前 respond 语句所在 Action 所对应的页面返回数据和对象。
  • 可以响应另外一个 GSP 页面,但是 URL 还是当前的 Action,不会执行另外的 GSP 页面对应的 Action。
  • respond 必须返回一个“对象”,然后加上其他的model等。
  • 有的时候需要使用 return 语句。
  • 根据“内容协商”配置的内容进行响应自动适应类型。
案例 参数类型 约定的前端变量
respond Book.list() java.util.List bookList
respond Book.get(1) example.Book book
respond( [1,2] ) java.util.List integerList
respond( [1,2] as Set ) java.util.Set integerSet
respond( [1,2] as Integer[] ) Integer[] integerArray

Demo

  • 默认的 show 页面,传递一个对象,和一组其他对象。
  • 可以选择最合适的类型进行响应
def show(Long id)
{
def layout = Layout.get(id)
def layoutPanel = LayoutPanel.findAllByLayout(layout, [sort: 'displayOrder', order: 'asc'])
respond layout, model: [layoutPanel: layoutPanel] // 默认的 show 页面,传递一个对象,和一组其他对象。
}
// 选择最合适的类型并转换格式进行响应
respond Book.get(1), formats: ['xml', 'json']

Demo

  • @Transactional + transactionStatus.setRollbackOnly() + return 保障对象异常的时候不保存数据。
  • respond layoutButton.errors, view: 'create', params: params 保障返回错误信息,传回必备的参数。
  • flash.message 保障存储成功后页面的提示信息。
@Transactional
def save(LayoutButton layoutButton)
{
if (layoutButton == null)
{
transactionStatus.setRollbackOnly()
notFound()
return
}
if (layoutButton.hasErrors())
{
transactionStatus.setRollbackOnly()
respond layoutButton.errors, view: 'create', params: params
return
}
layoutButton.save(flush: true)
request.withFormat {
form multipartForm {
flash.message = message(code: 'default.created.message', args: [message(code: 'layoutButton.label', default: 'LayoutButton'), layoutButton.id])
redirect url: params['targetUri']
}
'*' { respond layoutButton, [status: CREATED] }
}
}

参数

  • object 必选参数:需要响应的对象,这个是必须有的!
  • arguments 可选的参数

可选的参数

  • view - The view to use in case of HTML rendering(相应的页面)
  • model - The model to use in case of HTML rendering(可以相应各种类型的数据)
  • status - The response status(相应状态)
  • formats - A list of formats to respond with
  • includes - Properties to include if rendering with the converters API
  • excludes - Properties to exclude if rendering with the converters API
posted @   duchaoqun  阅读(238)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示