使用 Command 對象
在 action 參數中使用 command 對象,grails 會自動將 request 中的 json 串綁定到 command 對象的屬性上。
在此之後,不能再調用 request.JSON 來讀取 request body 內容了,否則報錯。
需要注意的是,出現下面情況,grails 將不會解析請求 body 中的 json 串:
- The request method is GET
- The request method is DELETE
- The content length is 0
Controller 自己解析 request body
方法一,使用 request.JSON 來讀取 body 並解析爲 json 對象。
def json = request.JSON
String phone = request.JSON["phone"]
方法二,使用輸入流
String bodyText = request.inputStream.text
String bodyText = request.inputStream.getText("UTF-8")
注意:Command 方法和 request 方法是互斥的,只能使用一種。
參考
參考 Grails Doc - theWebLayer 中的Binding The Request Body To Command Objects。