1

我的RESTjson 服务有问题。所有 REST 操作(POST、PUT、DELETE、GET)都有问题。我需要在每个操作中都有 IF-else 语句,但是出了点问题。例如,在 GET 操作中,我需要一些 if-else 案例。我想要findByName或 byid或 with which ever 字段。当我只使用一种情况(只有一种情况)时,我的程序可以正常工作。如果我使用多个 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
            }
    }
}
4

0 回答 0