5

Grails 是否默认支持 Restful 嵌套 URL,例如 '/articles/1/comments/5'?如果没有,是否有任何插件?

4

2 回答 2

6

这里。Grails 2.3 将支持嵌套的 RESTful URL。

于 2013-07-22T21:41:26.937 回答
5

如果您绑定到旧版本的 Grails(例如 < 2.3),并且可用的插件无法正常工作,您可以使用命名 URL 映射来生成有效的 restful 映射。

这是我的一个项目的一个例子——我遗漏了一些细节,但如果你决定尝试这种方法,希望这能让你开始。

在你的 UrlMappings.groovy

/** 1. Mappings can handle multiple actions depending on HTTP 
    method like Rest. Names are a little clunky, like this would
    be more appropriate as "resource" vs "showResource" but we didn't want
    potential naming conflict in future release 

    2. TODO: DRY constraints - make constraints global  
    3. make sure controllers have proper actions defined
*/

/** RESTFUL mapping for single resource */
name listResources: "/$controller" { 
  action = [GET: "list", POST: "save"] 
}
name createResource: "/$controller/create" { 
  action = [GET: "create" ] 
}
name deleteResource: "/$controller/$id?/delete" { 
  action = [POST: "delete", DELETE: "delete"] 
  constraints { id(matches: /[0-9]+/) }
}
name editResource: "/$controller/$id?/edit" { 
  action = [GET: "edit", PUT: "update", POST: "update"] 
  constraints { id(matches: /[0-9]+/) }
}
name showResource: "/$controller/$id?" { 
  action = [GET: "show", PUT: "update", POST: "update", DELETE: "delete"]
  constraints { id(matches: /[0-9]+/) }
}

/** RESTFUL mapping for CHILD with PARENT */
name listChildResources: "/$parentResource/$pid/$controller" { 
  action = [GET: "list", POST: "save"]
  constraints { pid(matches: /[0-9]+/) }
}
name createChildResource: "/$parentResource/$pid/$controller/create" {
  action = [GET: "create" ] 
  constraints { pid(matches: /[0-9]+/) }
}
name showChildResource: "/$parentResource/$pid/$controller/$id?" { 
  action = [GET: "show", PUT: "update", POST: "update", DELETE: "delete"] 
  constraints { 
    id(matches: /[0-9]+/)
    pid(matches: /[0-9]+/) 
  }
}
name editChildResource: "/$parentResource/$pid/$controller/$id?/edit" { 
  action = [GET: "edit"]
  constraints { 
    id(matches: /[0-9]+/)
    pid(matches: /[0-9]+/) 
  }
}

确保您的控制器定义了操作和支持的 HTTP 方法,例如

static allowedMethods = [
  save: "POST", 
  update: ["POST", "PUT"], 
  delete: ["POST", "DELETE"]
]

然后像这样使用映射(例如,假设我们有花园和植物作为资源)。

//show a garden
<g:link mapping="showResource" controller="garden" 
   id="${gardenInstance.id}">${gardenInstance.name}</g:link>

//create a plant for garden
<g:link mapping="createChildResource" controller="plant" 
   params="[parentResource: 'garden', pid: gardenInstance.id]">Add Plant</g:link>

//show list of plants within a garden
<g:link mapping="listChildResources" controller="plant" 
   params="[parentResource: 'garden', pid: gardenInstance.id]">List plants for Garden</g:link>

此处显示的内容非常冗长,但您可以将所有这些内容放入 TagLib 并拥有类似的东西。

<g:restShow resource="garden" 
   id="${gardenInstance.id}">${gardenInstance.name}</g:restShow>

<g:restCreate" resource="plant" 
   parent="${gardenInstance}">Add Plant</g:restCreate>
于 2013-07-22T22:33:55.730 回答