当前位置: 动力学知识库 > 问答 > 编程问答 >

json - Grails 2.5 REST PUT not getting called

问题描述:

Grails 2.4 RESTful controller.

I have a basic question. I have a RESTful controller with simple domain class and my GET, POST works fine.

How do I send PUT JSON request?

I am using default RESTful generated controllers

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"}

Then I tried PUT using same above JSON response (removed id:null and changed the username):

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

Request goes to index and I get list of users. What I am doing wrong? How do I invoke "update' method? If I add my own method and I do PUT, my own method gets invoked.

Domain class:

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 controller:

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 }

}

}

}

网友答案:

You're missing the call to user.validate() prior to calling hasErrors(). See

https://github.com/grails/grails-core/blob/master/grails-plugin-rest/src/main/groovy/grails/rest/RestfulController.groovy#L99

分享给朋友:
您可能感兴趣的文章:
随机阅读: