在学习任何东西之前,最重要的是培养兴趣,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:DMY_DEVgrails)
1,设置环境变量GRAILS_HOME(注意大写),过程与“设置环境变量GROOVY_HOME”相似。
2,将%GRAILS_HOME%bin添加到环境变量path中,过程与“将GROOVY_HOME目录下的bin追加到环境变量path中”相似。
(如果只想进行Grails开发,可以不设GROOVY_HOME)
二,创建Grails Demo程序
0,打开“命令行”,选择当前目录(我的为D:Tempgrails_apps),在黑底白字的窗口中输入“grails create-app demo”,不包括双引号“”,在您的屏幕中可以看到类似下面的输出结果:
D:Tempgrails_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:DMY_DEVgrails
Base Directory: D:Tempgrails_apps
Environment set to production
Note: No plugin scripts found
Running script D:DMY_DEVgrailsscriptsCreateApp.groovy
[mkdir] Created dir: D:Tempgrails_appsdemosrc
[mkdir] Created dir: D:Tempgrails_appsdemosrcjava
[mkdir] Created dir: D:Tempgrails_appsdemosrcgroovy
[mkdir] Created dir: D:Tempgrails_appsdemosrctest
[mkdir] Created dir: D:Tempgrails_appsdemograils-app
[mkdir] Created dir: D:Tempgrails_appsdemograils-appcontrollers
[mkdir] Created dir: D:Tempgrails_appsdemograils-appservices
[mkdir] Created dir: D:Tempgrails_appsdemograils-appdomain
[mkdir] Created dir: D:Tempgrails_appsdemograils-apptaglib
[mkdir] Created dir: D:Tempgrails_appsdemograils-apputils
[mkdir] Created dir: D:Tempgrails_appsdemograils-appviews
[mkdir] Created dir: D:Tempgrails_appsdemograils-appviewslayouts
[mkdir] Created dir: D:Tempgrails_appsdemograils-appi18n
[mkdir] Created dir: D:Tempgrails_appsdemograils-appconf
[mkdir] Created dir: D:Tempgrails_appsdemograils-tests
[mkdir] Created dir: D:Tempgrails_appsdemoscripts
[mkdir] Created dir: D:Tempgrails_appsdemoweb-app
[mkdir] Created dir: D:Tempgrails_appsdemoweb-appjs
[mkdir] Created dir: D:Tempgrails_appsdemoweb-appcss
[mkdir] Created dir: D:Tempgrails_appsdemoweb-appimages
[mkdir] Created dir: D:Tempgrails_appsdemoweb-appWEB-INFclasses
[mkdir] Created dir: D:Tempgrails_appsdemoweb-appMETA-INF
[mkdir] Created dir: D:Tempgrails_appsdemolib
[mkdir] Created dir: D:Tempgrails_appsdemospring
[mkdir] Created dir: D:Tempgrails_appsdemohibernate
[copy] Copying 2 files to D:Tempgrails_appsdemo
[copy] Copying 2 files to D:Tempgrails_appsdemoweb-appWEB-INF
[copy] Copying 1 file to D:Tempgrails_appsdemoweb-appWEB-INF
[copy] Copying 1 file to D:Tempgrails_appsdemoweb-appWEB-INF
[copy] Copying 5 files to D:Tempgrails_appsdemoweb-appWEB-INFtld
[copy] Copying 119 files to D:Tempgrails_appsdemoweb-app
[copy] Copying 1 file to D:Tempgrails_appsdemograils-appconf
[copy] Copying 1 file to D:Tempgrails_appsdemograils-appconf
[copy] Copying 1 file to D:Tempgrails_appsdemograils-appconf
[copy] Copying 7 files to D:Tempgrails_appsdemograils-app
[mkdir] Created dir: D:Tempgrails_appsdemopluginscoregrails-apptaglib
[mkdir] Created dir: D:Tempgrails_appsdemopluginscoregrails-apputils
[copy] Copying 7 files to D:Tempgrails_appsdemopluginscoregrails-app
taglib
[copy] Copying 3 files to D:Tempgrails_appsdemopluginscoregrails-app
utils
[copy] Copying 1 file to D:Tempgrails_appsdemospring
[copy] Copying 1 file to D:Tempgrails_appsdemo
[copy] Copying 1 file to D:Tempgrails_appsdemo
[copy] Copying 1 file to D:Tempgrails_appsdemo
Created Grails Application at D:Tempgrails_apps/demo
D:Tempgrails_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:Tempgrails_appsdemo>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:DMY_DEVgrails
Base Directory: D:Tempgrails_appsdemo
Environment set to production
Running script D:DMY_DEVgrailsscriptsCreateDomainClass.groovy
[copy] Copying 1 file to D:Tempgrails_appsdemograils-appdomain
Created at D:Tempgrails_appsdemo/grails-app/domain/User.groovy
[copy] Copying 1 file to D:Tempgrails_appsdemograils-tests
Created Tests at D:Tempgrails_appsdemo/grails-tests/UserTests.groovy
D:Tempgrails_appsdemo>
|
2,进入D:Tempgrails_appsdemograils-appdomain(这个目录中存放着所有的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:Tempgrails_appsdemo>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:DMY_DEVgrails
Base Directory: D:Tempgrails_appsdemo
Environment set to production
Running script D:DMY_DEVgrailsscriptsGenerateAll.groovy
Compiling sources
[delete] Deleting directory D:Tempgrails_appsdemoweb-appWEB-INFgrails-a
pp
[mkdir] Created dir: D:Tempgrails_appsdemoweb-appWEB-INFgrails-appvie
ws
[mkdir] Created dir: D:Tempgrails_appsdemoweb-appWEB-INFgrails-appi18
n
[copy] Copying 2 files to D:Tempgrails_appsdemoweb-appWEB-INFgrails-a
ppviews
[copy] Copied 2 empty directories to 1 empty directory under D:Tempgrails
_appsdemoweb-appWEB-INFgrails-appviews
[native2ascii] Converting 1 file from D:Tempgrails_appsdemograils-appi18n t
o D:Tempgrails_appsdemoweb-appWEB-INFgrails-appi18n
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:Tempgrails_appsdemo.grails-appviewsuserlist.gsp
Generating show view for domain class [User]
Show view generated at D:Tempgrails_appsdemo.grails-appviewsusershow.gsp
Generating edit view for domain class [User]
Edit view generated at D:Tempgrails_appsdemo.grails-appviewsuseredit.gsp
Generating create view for domain class [User]
Create view generated at D:Tempgrails_appsdemo.grails-appviewsusercreate
.gsp
Generating controller for domain class [User]
Controller generated at .grails-appcontrollersUserController.groovy
D:Tempgrails_appsdemo>
|
4,在“命令行”中,输入“grails create-controller Login”,创建登陆(login)的控制器LoginController,它对应MVC中的Controller,让它负责登陆相关业务,输出如下:
D:Tempgrails_appsdemo>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:DMY_DEVgrails
Base Directory: D:Tempgrails_appsdemo
Environment set to production
Running script D:DMY_DEVgrailsscriptsCreateController.groovy
[mkdir] Created dir: D:Tempgrails_appsdemograils-appviewslogin
[copy] Copying 1 file to D:Tempgrails_appsdemograils-appcontrollers
Created Controller at D:Tempgrails_appsdemo/grails-app/controllers/LoginContr
oller.groovy
[copy] Copying 1 file to D:Tempgrails_appsdemograils-tests
Created ControllerTests at D:Tempgrails_appsdemo/grails-tests/LoginController
Tests.groovy
D:Tempgrails_appsdemo>
|
5,修改demograils-appcontrollersLoginController.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 $"
render(view: "ok", model: [user: user])
} else {
flash.error = "Invalid $ with $"
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:Tempgrails_appsdemo>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:DMY_DEVgrails
Base Directory: D:Tempgrails_appsdemo
Environment set to production
Running script D:DMY_DEVgrailsscriptsCreateService.groovy
[copy] Copying 1 file to D:Tempgrails_appsdemograils-appservices
Created Service at D:Tempgrails_appsdemo/grails-app/services/LoginService.gro
ovy
[copy] Copying 1 file to D:Tempgrails_appsdemograils-tests
Created ServiceTests at D:Tempgrails_appsdemo/grails-tests/LoginServiceTests.
groovy
D:Tempgrails_appsdemo>
|
7,修改demograils-appservicesLoginService.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,修改demograils-appconfApplicationBootStrap.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:Tempgrails_appsdemo>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:DMY_DEVgrails
Base Directory: D:Tempgrails_appsdemo
Environment set to development
Running script D:DMY_DEVgrailsscriptsRunApp.groovy
Compiling sources
[delete] Deleting directory D:Tempgrails_appsdemoweb-appWEB-INFgrails-a
pp
[mkdir] Created dir: D:Tempgrails_appsdemoweb-appWEB-INFgrails-appvie
ws
[mkdir] Created dir: D:Tempgrails_appsdemoweb-appWEB-INFgrails-appi18
n
[copy] Copying 8 files to D:Tempgrails_appsdemoweb-appWEB-INFgrails-a
ppviews
[native2ascii] Converting 1 file from D:Tempgrails_appsdemograils-appi18n t
o D:Tempgrails_appsdemoweb-appWEB-INFgrails-appi18n
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:Tempgrails_appsdemoweb-appWEB-INFgrails-a
ppviews
[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
|
查看本文来源