如何根据内容类型请求标头以JSON或gsp视图呈现结果?

时间:2012-07-09 15:55:14

标签: grails

我想在控制器中为html-view和RESTful API重用相同的逻辑。 在Grails中这样做的最佳方法是什么?

1 个答案:

答案 0 :(得分:4)

我相信你正在寻找the withFormat method

(此处的代码取自添加了JSON的链接)

import grails.converters.XML
import grails.converters.JSON

class BookController {

    def list() {
        def books = Book.list()

        withFormat {
            html bookList:books
            js { render books as JSON }
            xml { render books as XML }
        }
    }
}