Grails 2.5 REST PUT没有被调用

时间:2014-07-03 02:23:07

标签: json grails

Grails 2.4 RESTful控制器。

我有一个基本问题。我有一个RESTful控制器与简单的域类和我的GET,POST工作正常。 如何发送PUT JSON请求? 我正在使用默认的RESTful生成的控制器

url -i -X POST -H "Content-Type: application/json" -d '{"roleId":1,"username":"testuser5"}' http://localhost:8090/testapp/User
HTTP/1.1 201 Created
Server: Apache-Coyote/1.1
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Thu, 03 Jul 2014 02:07:13 GMT

{"id":null,"userId":79,"username":"testuser5"}

然后我使用相同的JSON响应尝试了PUT(删除了id:null并更改了用户名):

curl -i -X PUT -H "Content-Type: application/json" -d '{"userId":79,"username":"testuser6"}' http://localhost:8090/testapp/User

请求转到索引,我获得用户列表。我做错了什么?我如何调用"更新'方法?如果我添加自己的方法并执行PUT,则会调用自己的方法。

域类:

class User {
    Integer userId
    String username

    static mapping = {
        table 'user'
        version false
        id name:'userId', column: 'user_id'
    }

    static constraints = {
        username blank:false, nullable:false
    }
}

RESTful控制器:

class UserController extends RestfulController {
    static responseFormats = ['json', 'xml']
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond User.list(params), model:[userInstanceCount: User.count()]
    }
    def show(User userInstance) {
        respond userInstance
    }
    def create() {
        respond new User(params)
    }

     @Transactional
    def update(User userInstance) {
        println "*** in update "
        if (userInstance == null) {
            notFound()
            return
        }

        if (userInstance.hasErrors()) {
            respond userInstance.errors, view:'edit'
            return
        }

        userInstance.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'User.label', default: 'User'), userInstance.id])
                redirect userInstance
            }
            '*'{ respond userInstance, [status: OK] }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }
}

1 个答案:

答案 0 :(得分:0)