2
我有1個域類,1個控制器,1個URL映射(見下文)。我想發送請求,並接收JSON響應。如何從Grails獲取JSON(或XML)響應?
但是,目前我的請求已正確映射到通訊員控制器方法,該方法已成功執行,然後收到錯誤消息,指出jsp文件不可用。
如何解釋Grails,我不需要沒有jsp文件:我想接收/解析JSON請求,並從我的控制器中直接發送JSON響應?
class Brand {
String name
String description
String logoImageURL
static constraints = {
name(blank: false)
}
}
---------------------------
class UrlMappings {
static mappings = {
"/brands"(controller: "brand", parseRequest: true, action: "list")
}
}
---------------------------
import grails.converters.JSON
class BrandController {
def list = {
return Brand.list() as JSON
}
def show = {
return Brand.get(params.id) as JSON
}
def save = {
def brand = new Brand(name: params.name, description: params.description, logoImageURL: params.logoURL)
if (brand.save()) {
render brand as JSON
} else {
render brand.errors
}
}
}
============== Error message ===============
Request URL: http://localhost:8080/ShoesShop/brands
message /ShoesShop/WEB-INF/grails-app/views/brand/list.jsp
description The requested resource (/ShoesShop/WEB-INF/grails-app/views/brand/list.jsp) is not available.
你也可以使用'withFormat' http://grails.org/doc/latest/ref/Controllers/withFormat.html如果你想提供JSON或XML服務(取決於消費者的請求)。如果你只想要JSON,那麼'作爲JSON'應該可以工作。 –
謝謝,夥計們。有用。 – Roman