本文为学习Grails的笔记,随着了解的深入会不断完善。
1、Grails是什么
Grails是一套用于快速Web应用开发的开源框架,它基于Groovy编程语言,并构建于Spring、Hibernate和其它标准Java框架之上。
2、安装
下载grails-2.2.0.zip,解压到本地目录,设置环境变量GRAILS_HOME指向zip解压目录,可能是
GRAILS_HOME=\path\to\grails
把%GRAILS_HOME%\bin添加到环境变量PATH中
在命令行环境下,运行grails,如果执行Ok,则安装完成。
运行grails help可以看到grails的使用方法
3、使用
要学会使用Grails,重要的是学会Grails命令行用法,Grails命令行基本语法如下:
grails [environment]* [options]* [target] [arguments]*
注:标*表示可选
grails的命令行参数比较多,可以先掌握几个重要的target参数(可以用grails help 'target-name'查看详细解释):
- grails create-app [NAME]:创建名为NAME的grails应用,例如grails create-app helloworld,将在当前目录下创建一个新目录helloword,helloworld目录下含有grails应用文件。创建应用后,转到该应用目录下执行后续操作。
- grails create-controller [NAME]:在grails-app\controllers目录下,创建名为NAME的grails控制器,例如grails create-controller hello,这将创建3个文件grails-app/controllers/helloworld/HelloController.groovy;grails-app/views/hello;test/unit/helloworld/HelloControllerTests.groovy。用记事本打开HelloController.groovy,将其内容修改为:
package helloworld class HelloController { def world = { render "Hello World!" } }
- grails run-app:运行grails应用。这将启动端口为8080的服务器(内置tomcat),在浏览器中输入URL:http://localhost:8080/helloworld,将出现结果页面,见下面截图:
4、在Eclipse中使用Grails
在Eclipse中安装 SpringSource Tool Suite(STS)后,将同时安装好Grails。
在Help菜单中启动Dashboard,然后选择Extensions页面,将列出所有可用的STS扩展,找到'Grails (current production release)'和 'Grails Support',点击install安装。
5、惯例优先原则
Grails的配置遵循惯例优先原则,即使用文件名称和位置代替精确的配置信息。下面是Grails应用的目录结构:
grails-app
- top level directory for Groovy sourcesconf
- Configuration sources.controllers
- Web controllers - The C in MVC.domain
- The application domain.i18n
- Support for internationalization (i18n).services
- The service layer.taglib
- Tag libraries.utils
- Grails specific utilities.views
- Groovy Server Pages - The V in MVC.
scripts
- Gant scripts.src
- Supporting sourcesgroovy
- Other Groovy sourcesjava
- Other Java sources
test
- Unit and integration tests.