请求参数和PUT方法

Igo*_*nov 9 java rest grails http

我正在尝试通过PUT请求传递请求参数,在基于Grails的应用程序.

我正在使用以下客户端代码发出请求:

$.ajax({
    url: 'api/controllerName/anId',
    type: 'PUT',
    data: $('form').serialize()
})
Run Code Online (Sandbox Code Playgroud)

使用以下映射:

"/api/$controller/$id?" {
    action = [ GET: "read", POST: "create", PUT: "update", DELETE: "delete"]
}
Run Code Online (Sandbox Code Playgroud)

但我的控制器的动作收到空的参数列表,只有id值.我试着将内容添加到日志中并仅查看:

[id:anId, action:[GET:read, POST:create, PUT:update, DELETE:delete], controller:controllerName]
Run Code Online (Sandbox Code Playgroud)

request.getParameterNames()返回空的值列表.

正如我在FireBug中看到的那样,请求包含此参数,并将Content-Type设置为 application/x-www-form-urlencoded; charset=UTF-8

如果我正在使用GET/POST方法 - 一切都按预期工作,我可以获得所有传递的参数.

我怎样才能访问传递的参数?

更新:我刚认为PUT意味着将数据作为JSON/XML传递到正文中.顺便说一句,这个问题仍然是实际的,以防万一

小智 8

我今天遇到了完全相同的问题,并且能够解决它.我用JQuery向Grails RESTful WebService(方法:"PUT")做了一个ajax请求,但是参数map是空的.

只想在这里分享我的解决方案.

我不得不JSON.stringify我的数据并将contentType设置为"application/json",然后在我的Grails控制器中使用request.JSON(如前所述).

示例(JQuery Ajax请求):

$.ajax({
        url: "/entries/" + id,
        contentType: "application/json",
        type: "PUT",
        dataType: "json",
        data: JSON.stringify({'name' : name, 'date': date}),
        success: function(msg) {
            console.log('updated...')
            $.mobile.changePage($('#list'));
        }
Run Code Online (Sandbox Code Playgroud)

之后我可以用:

request.JSON
Run Code Online (Sandbox Code Playgroud)

在我的Controller中,为了获取ajax请求发送的数据(params仍为空).如果我没有使用JSON.stringify并设置内容类型,我有以下Grails错误:

Error 2012-04-03 13:50:20,046 [http-bio-8080-exec-3] ERROR errors.GrailsExceptionResolver  - IllegalStateException occurred when processing request: [PUT] /entries/2
getReader() has already been called for this request. Stacktrace follows:
Message: getReader() has already been called for this request
Run Code Online (Sandbox Code Playgroud)

我正在使用Grails 2.0.1和JQuery 1.7.1