如何在Grails 2.3中一起使用scaffolding和RESTfulness

aka*_*_sh 11 rest grails scaffolding

官方Grails文档说明了这一点

脚手架插件的2.0.x版包含不同的脚手架模板,这些模板与Grails 2.3及更高版本中的新REST API一致.(摘自http://grails.org/doc/latest/guide/scaffolding.html)

但我无法制作(或者我不理解这个概念)与脚手架一起工作RESTfulness.

让我们从头开始:

grails create-app myapp
cd myapp/
grails create-domain-class Book
grails create-scaffold-controller myapp.Book
Run Code Online (Sandbox Code Playgroud)

将字段添加到域类

class Book {
    String text

    static constraints = {
    }
}
Run Code Online (Sandbox Code Playgroud)

然后运行应用程序grails run-app.在http://localhost:8080/myapp/脚手架上运行很棒的节目上冲浪:

  • http://localhost:8080/myapp/book/index 页面显示书籍列表
  • http://localhost:8080/myapp/book/show/1 页面显示id为1的图书的详细信息
  • http://localhost:8080/myapp/book/create 页面创建一本书
  • 所以力,好旧的脚手架.

我们来看看REST的情况.官方文档称我应该使用类似于http://localhost:8080/myapp/books/...REST的URL ,但是任何尝试访问应用程序的方式都是如此,这样就会curl -i -H "Accept: application/json" localhost:8080/myapp/books/1返回带有大量HTML的404.

好的,让我们仔细阅读文档:

在Grails中创建RESTful API的最简单方法是将域类公开为REST资源.这可以通过将grails.rest.Resource转换添加到任何域类来完成

没问题,现在Book类标题是

import grails.rest.*

@Resource(uri='/books') class Book {
Run Code Online (Sandbox Code Playgroud)

现在冲上http://localhost:8080/myapp/脚手架被打破的节目:

  • http://localhost:8080/myapp/book/index 页面显示书籍列表
  • http://localhost:8080/myapp/book/create 页面显示xml输出 <?xml version="1.0" encoding="UTF-8"?><book><text /></book>
  • 所以强制,坏的新xml输出.

我在URLMappings.groovy 中使用@Resource"/ books"(资源:"book"),但没有找到任何可行的解决方案,这使得脚手架和RESTfulness可以背靠背地工作.实际上,我设法让它们分开工作.

更新

我找到了如何实现预期目标的方法.我发现的方式是:

  1. 标记Book@Resource(uri = "/books").
  2. 删除脚手架控制器BookController.
  3. 为本书创建带脚手架的专用控制器: class HumanBookController {static scaffold = Book}

现在,带有URL的脚手架GUI页面http://localhost:8080/myapp/humanBook/index工作得很好.使用像这样的URL处理json请求http://localhost:8080/myapp/books/1.但是让2个控制器为普通的web和json做同样的事情并不优雅.

eva*_*ong 15

你可以这样做:

import grails.rest.RestfulController

class BookController extends RestfulController {

    static responseFormats = ['html', 'json']

    BookController() {
        super(Book)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在UrlMappings.groovy中:

 "/books"(resources:"book")
 "/$controller/$action?/$id?(.${format})?"{
    constraints {
        // apply constraints here
    }
  }
Run Code Online (Sandbox Code Playgroud)

无需在域中添加@Resource.您现在可以将/books/1.json或/books/1.html指向正确的位置.您可能仍需要执行grails generate-view Book生成视图.但是,虽然您需要为html生成视图,但您只保留单个控制器和路径.