下面我们通过一个简单的例子来创建一个Grails工程。
创建一个 Grails project
我们通过第一章安装配置好Grails的工作环境后,可以通过命令行来创建一个工程:(首先进入到要创建的目录下)
grails create-app my-project
%PROJECT_HOME% + grails-app + conf ---> location of configuration artifacts
+ hibernate ---> optional hibernate config
+ spring ---> optional spring config
+ controllers ---> location of controller artifacts
+ domain ---> location of domain classes
+ i18n ---> location of message bundles for i18n
+ services ---> location of services
+ taglib ---> location of tag libraries
+ util ---> location of special utility classes
+ views ---> location of views
+ layouts ---> location of layouts
+ lib
+ scripts ---> scripts
+ src
+ groovy ---> optional; location for Groovy source files
(of types other than those in grails-app/*)
+ java ---> optional; location for Java source files
+ test ---> generated test classes
+ web-app
+ WEB-INF
创建一个 Domain Class
Grails的核心思想就是domain model, 下面就是创建一个Domain Class:
cd my-projectgrails create-domain-class org.example.Book
这个命令会创建一个Book.groovy类,
在 grails-app/domain/org/example目录下
。
注: 数据库表的名称会自动根据Domain Class生成 。我们要注意Domain Class的名称不要用数据库的关键字,不然会发生冲突 。
下面我们继续编写我们的Domain Class:
package org.exampleclass Book { String title String author
static constraints = { title(blank: false) author(blank: false) } }
上面的代码的作用是,当我们保存Book时
, 它
的title和
author被保存到数据库 。
constraints :允许你指定你的Domain Class的属性的验证要求。在这里我们可以对每个字段进行相关的验证。你甚至可以添加自己的验证方法,具体的信息可以查看看用户指南上验证的相关信息。
创建一个controller
Controllers are central to generating your user interface or providing a programmatic REST interface. They typically handle the web requests that come from a browser or some other client and you'll find that each URL of your application is usually handled by one controller.
Grails provides a feature called scaffolding that automatically creates a user interface for a domain class that allows you create new instances, modify them, and delete them. Enabling scaffolding is very straightforward. We start by creating a controller for our domain class:
Controllers 是与页面交互的类,提供REST编程接口 。通常从浏览器或其他客户端来处理Web请求,每次URL请求都是通过Controllers处理。
Grails提供了脚手架的一个功能,可以根据Domain Class自动创建一个Controllers类,可对它们进行修改。启用脚手架是非常简单的。我们开始创建我们的Controllers:
grails create-controller org.example.Book // Note the capital B
注意我们用的是Domain Class的完整类名,包括包 。此命令创建文件grails-app/controllers/org/example/BookController.groovy
包含我们的Controllers代码。请注意,Controllers Class的后缀名为Controller ,表示为一个Controllers Class。
打开刚才生成的Controllers Class并对其进行修改,内容如下:
package org.exampleclass BookController { def scaffold = Book // Note the capital "B" }
运行 Grails
运行我们刚才生成的应用程序使用下面命令:
grails run-app
运行后会启动Tomcat,我们会看一个默认的欢迎页面,上面有一个Controllers Class的一个链接,点击链接,我们就可以看到页面了。