控制器中的Grails Restful Json问题

时间:2013-05-07 22:43:11

标签: json rest grails groovy controller

我遇到REST json服务的问题。我的所有REST操作都有问题(POST,PUT,DELETE,GET)。我需要在每个操作中都有IF-else语句,但是出了问题。例如,在GET操作中,我需要一些if-else情况。我想要findByNameid或者哪些字段。当我只使用一个案例(只有一个案例)时,我的程序工作正常。如果我使用多个if-else语句,则程序不起作用。我对DELETE也有同样的问题。我究竟做错了什么?该怎么办?

感谢

def index = {
    switch (request.method) {

        case "POST":
            def trip = new Trip(params.trip)

            if (trip.save()) {
                response.status = 201 // Created
                render trip as JSON
            } else {
                response.status = 500 //Internal Server Error
                render "Could not create new Trip due to errors:\n ${trip.errors}"
            }
            break
        case "GET":
            if (params.city) render Trip.findByCity(params.city) as JSON

            // else if(params.name)render Trip.findByName(params.name) as JSON
            //else if(params.city)render Trip.findByCity(params.city)as JSON
            // else render Trip.list() as JSON
            break
        case "PUT":
            def trip = Trip.get(params.name)
            trip.properties = params.Trip
            if (trip.save()) {
                response.status = 200 // OK
                render trip as JSON
            } else {
                response.status = 500 //Internal Server Error
                render "Could not create new Trip due to errors:\n ${trip.errors}"
            }
            break
            break
        case "DELETE":
            if (params.name) {
                def trip = Trip.findByName(params.name)
                if (trip) {
                    trip.delete()
                    render "Successfully Deleted."
                } else {
                    response.status = 404 //Not Found
                    render "${params.name} not found."
                }
            } else {
                response.status = 400 //Bad Request
                render """DELETE request must include the NAME code
                  Example: /rest/airport/name
        """
                break
            }
    }
}

0 个答案:

没有答案