Grails UrlMappings for Rest和其他动作

时间:2015-10-30 07:17:10

标签: grails

我有一个控制器,主要用于使用showupdatesavedelete操作进行REST通信。这相应地映射到UrlMappings.groovy文件中并且工作得很好。

然后我需要在同一个控制器中调用getAccountTypesByEnv动作,但是我在设置实际有效的语法时遇到了一些麻烦。

以下定义有效,但我想知道是否有更简单,更正确的方法。

"/ext/accounttype/$id?"(controller: "accountType") {
    action = [GET: 'show', PUT: 'update', POST: 'save', DELETE: 'delete']
    "/ext/accounttype/getAccountTypesByEnv"(controller: "accountType", action: "getAccountTypesByEnv")
}

更新

我最终将其划分为2个单独的通用映射,如下所示:

"/ext/$controller/$id?" {
     action = [GET: 'show', PUT: 'update', POST: 'save', DELETE: 'delete']
}

"/ext/$controller/action/$customAction?" {
     action = { return params.customAction }
}

1 个答案:

答案 0 :(得分:1)

您可以在UrlMappings.groovy中定义:

 "/ext/$controller/$resourceId?/$customAction?" {
    action = {
        Map actionMethodMap = [GET: params.resourceId ? "show" : "index", POST: "save", PUT: "update", DELETE: "delete"]

        return params.customAction ?: actionMethodMap[request.method.toUpperCase()]
    }
    id = {
        if (params.resourceId == "action") {
            return params.id
        }
        return params.resourceId
    }
}

这是我现在认为最通用的UrlMapping,你可以通过以下方式使用它:

GET     "/ext/accounttype" will call **index** action of AccounttypeController
POST    "/ext/accounttype" will call save action of AccounttypeController
PUT     "/ext/accounttype/14" will call update action of AccounttypeController with id 14
DELETE  "/ext/accounttype/14" will call update action of AccounttypeController with id 14
GET     "/ext/accounttype/14" will call show action of AccounttypeController with id 14
GET     "/ext/accounttype/action/getAccountTypesByEnv" will call getAccountTypesByEnv action of AccounttypeController with null id
GET     "/ext/accounttype/action/getAccountTypesByEnv?id=143" will call getAccountTypesByEnv action of AccounttypeController with id 143