【问题标题】:Grails Restful Controller UPDATE-Method does not take updated Data from PUTGrails Restful 控制器更新方法不从 PUT 获取更新的数据
【发布时间】:2015-07-02 17:51:42
【问题描述】:

我在我的 Grails 2.3.5 应用程序中设置了一个 Restful 控制器。通过 PUT 将对象发送到我的端点时,该对象不会得到更新。我的 println 没有显示更新的数据,而是显示原始数据。我不明白为什么。

Restful 控制器

import grails.rest.RestfulController

class PluginSettingController extends RestfulController {
    static responseFormats = ['json', 'xml']

    PluginSettingController() {
        super(PluginSetting)
    }

    @Override
    def update(PluginSetting setting){
        println(setting.name)
        // This prints out the old name: "Old name"
    }

域类:

class PluginSetting {
    String name
    String value

    static constraints = {
        name(nullable:false, blank:false, unique: true)
        value(nullable:false, blank:false)
    }
}

卷曲请求:

curl -i -X PUT -d "{'name':'NEW','value':'my value', 'id':1}" http://localhost:8080/app/pluginSettings/1

旧对象(这是我在向 URL 'http://localhost:8080/app/pluginSettings/1' 发送 GET 时得到的)

{
    "class": "configuration.PluginSetting",
    "id": 1,
    "name": "Old name",
    "value": "my value"
} 

【问题讨论】:

  • 网址映射? debug 告诉你什么参数值在 update() 中?
  • 调试告诉我什么。但我发现了错误。缺少内容类型:-H "Content-Type: application/json"

标签: rest grails controller


【解决方案1】:

这终于在 Grails 2.5.4 上为我工作了 - 令人惊讶的是,在使用第二个控制器时正常方法不起作用。

@Transactional(readOnly=false)  // not needed
class EngineController extends RestfulController<PluginSettings> {
    static responseFormats = ['json', 'xml']
    EngineController() {
        super(PluginSettings)
    }
}

class UrlMappings {
    static mappings = {
        "/$controller/$action?/$id?(.$format)?"{
            constraints {
               // apply constraints here
           }
        }

        "/"(view:"/index")
        "500"(view:'/error')
    }
}

#Show
curl -i -X GET -H "Accept: application/json" localhost:8080/app/engine/index
curl -i -X GET -H "Accept: application/json" localhost:8080/app/engine/show/1
#Create
curl -i -X POST -H "Content-Type: application/json" -d '{"name":"Along Came A Spider"}' localhost:8080/app/engine/save
#Update
curl -i -X PUT -H "Content-Type: application/json" -d '{"name":"Along Came A Spider"}' localhost:8080/app/engine/update/1
#Delete
curl -i -X DELETE http://localhost:8080/app/engine/delete/1

但是,当我修改 urlMappings 以包含时

"/api/engines"(resources:"Engine")

我不得不使用

curl -i -X GET -H "Accept: application/json" localhost:8080/app/api/engines/
curl -i -X GET -H "Accept: application/json" localhost:8080/app/api/engines/1
curl -i -X POST -H "Content-Type: application/json" -d '{"name":"Along Came A Spider"}' localhost:8080/app/api/engines/
curl -i -X PUT -H "Content-Type: application/json" -d '{"name":"Along Came A Spider"}' localhost:8080/app/api/engines/1
curl -i -X DELETE http://localhost:8080/app/api/engines/1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-16
    • 2022-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 2015-06-14
    • 2019-03-21
    相关资源
    最近更新 更多