科技行者

行者学院 转型私董会 科技行者专题报道 网红大战科技行者

知识库

知识库 安全导航



ZDNet>软件频道>中间件-zhiding>Groovy轻松入门——Grails实战基础篇

  • 扫一扫
    分享文章到微信

  • 扫一扫
    关注官方公众号
    至顶头条

在学习任何东西之前,最重要的是培养兴趣,Groovy世界最耀眼的技术之一

来源:蛟龍居 2007年11月18日

关键字:Grails 入门 Groovy

在学习任何东西之前,最重要的是培养兴趣,Groovy世界最耀眼的技术之一--Grails相信大家早已耳闻,我将通过Grails实战系列文章向您展现Grails的迷人风采,使您感受到Grails的魅力,以至疯狂地爱上Grails,并坠入Groovy的爱河。学Groovy,Grails与学Java一样,在实战之前需要搭建开发环境,您可以在 Groovy轻松入门--搭建Groovy开发环境 学习到如何搭建Groovy环境,之后我会讲一下如何搭建Grails环境,然后手把手地写个Demo程序告终,我还会抽空写篇“Groovy轻松入门--Grails实战之进阶篇”

一,搭建Grails环境

0,下载Grails( http://dist.codehaus.org/grails/grails-bin-0.4.2.zip ,请留意朝花夕拾——Groovy & Grails中的“最新版本”提示)并解压到自己指定位置(我的位置是D:\D\MY_DEV\grails)

1,设置环境变量GRAILS_HOME(注意大写),过程与“设置环境变量GROOVY_HOME”相似。

2,将%GRAILS_HOME%\bin添加到环境变量path中,过程与“将GROOVY_HOME目录下的bin追加到环境变量path中”相似。

(如果只想进行Grails开发,可以不设GROOVY_HOME)

二,创建Grails Demo程序

0,打开“命令行”,选择当前目录(我的为D:\Temp\grails_apps),在黑底白字的窗口中输入“grails create-app demo”,不包括双引号“”,在您的屏幕中可以看到类似下面的输出结果:

D:\Temp\grails_apps>grails create-app demo

Welcome to Grails 0.4.2 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: D:\D\MY_DEV\grails

Base Directory: D:\Temp\grails_apps
Environment set to production
Note: No plugin scripts found
Running script D:\D\MY_DEV\grails\scripts\CreateApp.groovy
    [mkdir] Created dir: D:\Temp\grails_apps\demo\src
    [mkdir] Created dir: D:\Temp\grails_apps\demo\src\java
    [mkdir] Created dir: D:\Temp\grails_apps\demo\src\groovy
    [mkdir] Created dir: D:\Temp\grails_apps\demo\src\test
    [mkdir] Created dir: D:\Temp\grails_apps\demo\grails-app
    [mkdir] Created dir: D:\Temp\grails_apps\demo\grails-app\controllers
    [mkdir] Created dir: D:\Temp\grails_apps\demo\grails-app\services
    [mkdir] Created dir: D:\Temp\grails_apps\demo\grails-app\domain
    [mkdir] Created dir: D:\Temp\grails_apps\demo\grails-app\taglib
    [mkdir] Created dir: D:\Temp\grails_apps\demo\grails-app\utils
    [mkdir] Created dir: D:\Temp\grails_apps\demo\grails-app\views
    [mkdir] Created dir: D:\Temp\grails_apps\demo\grails-app\views\layouts
    [mkdir] Created dir: D:\Temp\grails_apps\demo\grails-app\i18n
    [mkdir] Created dir: D:\Temp\grails_apps\demo\grails-app\conf
    [mkdir] Created dir: D:\Temp\grails_apps\demo\grails-tests
    [mkdir] Created dir: D:\Temp\grails_apps\demo\scripts
    [mkdir] Created dir: D:\Temp\grails_apps\demo\web-app
    [mkdir] Created dir: D:\Temp\grails_apps\demo\web-app\js
    [mkdir] Created dir: D:\Temp\grails_apps\demo\web-app\css
    [mkdir] Created dir: D:\Temp\grails_apps\demo\web-app\images
    [mkdir] Created dir: D:\Temp\grails_apps\demo\web-app\WEB-INF\classes
    [mkdir] Created dir: D:\Temp\grails_apps\demo\web-app\META-INF
    [mkdir] Created dir: D:\Temp\grails_apps\demo\lib
    [mkdir] Created dir: D:\Temp\grails_apps\demo\spring
    [mkdir] Created dir: D:\Temp\grails_apps\demo\hibernate
     [copy] Copying 2 files to D:\Temp\grails_apps\demo
     [copy] Copying 2 files to D:\Temp\grails_apps\demo\web-app\WEB-INF
     [copy] Copying 1 file to D:\Temp\grails_apps\demo\web-app\WEB-INF
     [copy] Copying 1 file to D:\Temp\grails_apps\demo\web-app\WEB-INF
     [copy] Copying 5 files to D:\Temp\grails_apps\demo\web-app\WEB-INF\tld
     [copy] Copying 119 files to D:\Temp\grails_apps\demo\web-app
     [copy] Copying 1 file to D:\Temp\grails_apps\demo\grails-app\conf
     [copy] Copying 1 file to D:\Temp\grails_apps\demo\grails-app\conf
     [copy] Copying 1 file to D:\Temp\grails_apps\demo\grails-app\conf
     [copy] Copying 7 files to D:\Temp\grails_apps\demo\grails-app
    [mkdir] Created dir: D:\Temp\grails_apps\demo\plugins\core\grails-app\taglib

    [mkdir] Created dir: D:\Temp\grails_apps\demo\plugins\core\grails-app\utils
     [copy] Copying 7 files to D:\Temp\grails_apps\demo\plugins\core\grails-app\
taglib
     [copy] Copying 3 files to D:\Temp\grails_apps\demo\plugins\core\grails-app\
utils
     [copy] Copying 1 file to D:\Temp\grails_apps\demo\spring
     [copy] Copying 1 file to D:\Temp\grails_apps\demo
     [copy] Copying 1 file to D:\Temp\grails_apps\demo
     [copy] Copying 1 file to D:\Temp\grails_apps\demo
Created Grails Application at D:\Temp\grails_apps/demo
D:\Temp\grails_apps>

通过“grails create-app”这个命令,Grails自动帮我们创建了开发所需的工程环境。其实您现在就已经拥有了一个可运行的Web应用程序,然后进入demo目录(“cd demo”),输入“grails run-app”,回车,启动这个‘五脏俱全’的程序雏形,打开浏览器,输入 http://localhost:8080/demo ,回车,看到了吧 :) 让我们继续吧,请停止这个程序(Ctrl + C)

1,进入demo目录,在“命令行”中输入“cd demo”,回车,然后再输入“grails create-domain-class User”创建domain class即类似于pojo的pogo,它对应MVC中的Model,不过由Grails自动创建的pogo是空的,需要自己添加属性,约束(constraints)等。输出结果如下所示:

D:\Temp\grails_apps\demo>grails create-domain-class User

Welcome to Grails 0.4.2 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: D:\D\MY_DEV\grails

Base Directory: D:\Temp\grails_apps\demo
Environment set to production
Running script D:\D\MY_DEV\grails\scripts\CreateDomainClass.groovy
     [copy] Copying 1 file to D:\Temp\grails_apps\demo\grails-app\domain
Created  at D:\Temp\grails_apps\demo/grails-app/domain/User.groovy
     [copy] Copying 1 file to D:\Temp\grails_apps\demo\grails-tests
Created Tests at D:\Temp\grails_apps\demo/grails-tests/UserTests.groovy
D:\Temp\grails_apps\demo>

2,进入D:\Temp\grails_apps\demo\grails-app\domain(这个目录中存放着所有的domain class),打开User.groovy,修改为如下内容:

class   User { 
    String name
    String password
    
    String toString() {
         " $name : $password "     
    }
    
     static  constraints  =  {
        name(blank:  false )    
        password(blank:  false , size:  6 .. 16 )
    }
contraints这个类变量是定义一些约束的,比如name不能为空白,password不能为空白而且长度在6到16之间(包括6和16)
3,在“命令行”中输入“grails generate-all User”,为User产生所有CRUD操作需要的代码(如控制器UserController.groovy)和页面(如list.gsp),输出结果如下所示:
D:\Temp\grails_apps\demo>grails generate-all User

Welcome to Grails 0.4.2 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: D:\D\MY_DEV\grails

Base Directory: D:\Temp\grails_apps\demo
Environment set to production
Running script D:\D\MY_DEV\grails\scripts\GenerateAll.groovy
Compiling sources
   [delete] Deleting directory D:\Temp\grails_apps\demo\web-app\WEB-INF\grails-a
pp
    [mkdir] Created dir: D:\Temp\grails_apps\demo\web-app\WEB-INF\grails-app\vie
ws
    [mkdir] Created dir: D:\Temp\grails_apps\demo\web-app\WEB-INF\grails-app\i18
n
     [copy] Copying 2 files to D:\Temp\grails_apps\demo\web-app\WEB-INF\grails-a
pp\views
     [copy] Copied 2 empty directories to 1 empty directory under D:\Temp\grails
_apps\demo\web-app\WEB-INF\grails-app\views
[native2ascii] Converting 1 file from D:\Temp\grails_apps\demo\grails-app\i18n t
o D:\Temp\grails_apps\demo\web-app\WEB-INF\grails-app\i18n
Attempting to load [13] core plugins
Grails plug-in [i18n] with version [0.4.2] loaded successfully
Grails plug-in [quartz] with version [0.4.2] loaded successfully
Grails plug-in [core] with version [0.4.2] loaded successfully
Grails plug-in [domainClass] with version [0.4.2] loaded successfully
Grails plug-in [controllers] with version [0.4.2] loaded successfully
Attempting to load [0] user defined plugins
Grails plug-in [dataSource] with version [0.4.2] loaded successfully
Grails plug-in [codecs] with version [0.4.2] loaded successfully
Grails plug-in [hibernate] with version [0.4.2] loaded successfully
Grails plug-in [services] with version [0.4.2] loaded successfully
Grails plug-in [scaffolding] with version [0.4.2] loaded successfully
Generating views for domain class [User]
Generating list view for domain class [User]
list view generated at D:\Temp\grails_apps\demo\.\grails-app\views\user\list.gsp

Generating show view for domain class [User]
Show view generated at D:\Temp\grails_apps\demo\.\grails-app\views\user\show.gsp

Generating edit view for domain class [User]
Edit view generated at D:\Temp\grails_apps\demo\.\grails-app\views\user\edit.gsp

Generating create view for domain class [User]
Create view generated at D:\Temp\grails_apps\demo\.\grails-app\views\user\create
.gsp
Generating controller for domain class [User]
Controller generated at .\grails-app\controllers\UserController.groovy
D:\Temp\grails_apps\demo>

4,在“命令行”中,输入“grails create-controller Login”,创建登陆(login)的控制器LoginController,它对应MVC中的Controller,让它负责登陆相关业务,输出如下:

D:\Temp\grails_apps\demo>grails create-controller Login

Welcome to Grails 0.4.2 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: D:\D\MY_DEV\grails

Base Directory: D:\Temp\grails_apps\demo
Environment set to production
Running script D:\D\MY_DEV\grails\scripts\CreateController.groovy
    [mkdir] Created dir: D:\Temp\grails_apps\demo\grails-app\views\login
     [copy] Copying 1 file to D:\Temp\grails_apps\demo\grails-app\controllers
Created Controller at D:\Temp\grails_apps\demo/grails-app/controllers/LoginContr
oller.groovy
     [copy] Copying 1 file to D:\Temp\grails_apps\demo\grails-tests
Created ControllerTests at D:\Temp\grails_apps\demo/grails-tests/LoginController
Tests.groovy
D:\Temp\grails_apps\demo>

5,修改demo\grails-app\controllers\LoginController.groovy的内容为:

class LoginController {
    def loginService

    def index = { }
    
    def login = {
        User u = new User()
        u.properties = params
        if (params.name && params.password) {

            def user = loginService.check(u)
            
            if (user) {
                flash.message = "Welcome ${user.name}" 
                render(view: "ok", model: [user: user])
            } else {
                flash.error = "Invalid ${u.name} with ${u.password}"
                render(view: "login", model: [user: u])
            }    
        } else {
            render(view: "login", model: [user: u])
        }
    }
}

大家或许也看到了LoginService这个类,我将在后面演示创建它,这个LoginService类封装了所有登陆相关的业务逻辑,Grails自动将其注入到LoginController中。

6,在“命令行”中,输入“grails create-service Login”,创建LoginService.groovy,输出:

D:\Temp\grails_apps\demo>grails create-service Login

Welcome to Grails 0.4.2 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: D:\D\MY_DEV\grails

Base Directory: D:\Temp\grails_apps\demo
Environment set to production
Running script D:\D\MY_DEV\grails\scripts\CreateService.groovy
     [copy] Copying 1 file to D:\Temp\grails_apps\demo\grails-app\services
Created Service at D:\Temp\grails_apps\demo/grails-app/services/LoginService.gro
ovy
     [copy] Copying 1 file to D:\Temp\grails_apps\demo\grails-tests
Created ServiceTests at D:\Temp\grails_apps\demo/grails-tests/LoginServiceTests.
groovy
D:\Temp\grails_apps\demo>

7,修改demo\grails-app\services\LoginService.groovy的内容为:

class LoginService {
    
    boolean transactional = true
    
    def check(User u) {
        def user = User.findWhere(name: u.name, password: u.password)
        return user
    }
    
    def serviceMethod() {
        // TODO
    }
}
 

ok.gsp:

9,修改demo\grails-app\conf\ApplicationBootStrap.groovy,将一个User实例保存到数据库(grails自带hsqldb和jetty)中,内容如下:

class ApplicationBootStrap {

     def init = { servletContext ->
         new User(name: "demo", password: "123456").save()
     }
     def destroy = {
     }
} 

 

10,在“命令行”中,输入“grails run-app”,运行我们的Web应用,输出如下:

D:\Temp\grails_apps\demo>grails run-app

Welcome to Grails 0.4.2 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: D:\D\MY_DEV\grails

Base Directory: D:\Temp\grails_apps\demo
Environment set to development
Running script D:\D\MY_DEV\grails\scripts\RunApp.groovy
Compiling sources
   [delete] Deleting directory D:\Temp\grails_apps\demo\web-app\WEB-INF\grails-a
pp
    [mkdir] Created dir: D:\Temp\grails_apps\demo\web-app\WEB-INF\grails-app\vie
ws
    [mkdir] Created dir: D:\Temp\grails_apps\demo\web-app\WEB-INF\grails-app\i18
n
     [copy] Copying 8 files to D:\Temp\grails_apps\demo\web-app\WEB-INF\grails-a
pp\views
[native2ascii] Converting 1 file from D:\Temp\grails_apps\demo\grails-app\i18n t
o D:\Temp\grails_apps\demo\web-app\WEB-INF\grails-app\i18n
Attempting to load [13] core plugins
Grails plug-in [i18n] with version [0.4.2] loaded successfully
Grails plug-in [quartz] with version [0.4.2] loaded successfully
Grails plug-in [core] with version [0.4.2] loaded successfully
Grails plug-in [domainClass] with version [0.4.2] loaded successfully
Grails plug-in [controllers] with version [0.4.2] loaded successfully
Attempting to load [0] user defined plugins
Grails plug-in [dataSource] with version [0.4.2] loaded successfully
Grails plug-in [codecs] with version [0.4.2] loaded successfully
Grails plug-in [hibernate] with version [0.4.2] loaded successfully
Grails plug-in [services] with version [0.4.2] loaded successfully
Grails plug-in [scaffolding] with version [0.4.2] loaded successfully
[RuntimeConfiguration] Configuring for environment: Development
Building new Hibernate SessionFactory
Neither 'urlMap' nor 'mappings' set on SimpleUrlHandlerMapping
64 beans defined in application context [org.codehaus.groovy.grails.commons.spri
ng.GrailsWebApplicationContext;hashCode=6971605]
Using MessageSource [org.springframework.context.support.ReloadableResourceBundl
eMessageSource: basenames=[WEB-INF/grails-app/i18n/messages]]
Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticas
ter': using default [org.springframework.context.event.SimpleApplicationEventMul
ticaster@181d405]
     [copy] Copying 8 files to D:\Temp\grails_apps\demo\web-app\WEB-INF\grails-a
pp\views
[GrailsContextLoader] Grails application loaded.
Initializing filter 'grailsWebRequest'
Filter 'grailsWebRequest' configured successfully
Initializing filter 'reloadFilter'
Filter 'reloadFilter' configured successfully
Initializing servlet 'grails'
FrameworkServlet 'grails': initialization started
Using context class [org.codehaus.groovy.grails.commons.spring.GrailsWebApplicat
ionContext] for servlet 'grails'
Using MultipartResolver [org.springframework.web.multipart.commons.CommonsMultip
artResolver@1945696]
Using LocaleResolver [org.springframework.web.servlet.i18n.CookieLocaleResolver@
1c0bec5]
Unable to locate ThemeResolver with name 'themeResolver': using default [org.spr
ingframework.web.servlet.theme.FixedThemeResolver@1984161]
No HandlerAdapters found in servlet 'grails': using default
Unable to locate RequestToViewNameTranslator with name 'viewNameTranslator': usi
ng default [org.springframework.web.servlet.view.DefaultRequestToViewNameTransla
tor@688d6f]
FrameworkServlet 'grails': initialization completed in 187 ms
Servlet 'grails' configured successfully

11,打开浏览器,输入:http://localhost:8080/demo/login/login ,在Name处输入demo,Password处输入123456,点击‘Login’,跳转到成功页面:

Welcome demo
demo : 123456

查看本文来源

推广二维码
邮件订阅

如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。

重磅专题