Groovy輕鬆入門——Grails實戰基礎篇

來源:互聯網
上載者:User
在學習任何東西之前,最重要的是培養興趣,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-1.0.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程式3,開啟“命令列”,選擇目前的目錄(我的為D:\Temp\grails_apps),在黑底白字的視窗中輸入“grails create-app demo”,不包括雙引號“”,在您的螢幕中可以看到類似下面的輸出結果:D:\_DEV\grails_apps>grails create-app demoWelcome to Grails 1.0 - http://grails.org/Licensed under Apache Standard License 2.0Grails home is set to: D:\D\MY_DEV\grails-1.0Base Directory: D:\_DEV\grails_appsEnvironment set to developmentNote: No plugin scripts foundRunning script D:\D\MY_DEV\grails-1.0\scripts\CreateApp.groovy [mkdir] Created dir: D:\_DEV\grails_apps\demo\src [mkdir] Created dir: D:\_DEV\grails_apps\demo\src\java [mkdir] Created dir: D:\_DEV\grails_apps\demo\src\groovy [mkdir] Created dir: D:\_DEV\grails_apps\demo\grails-app [mkdir] Created dir: D:\_DEV\grails_apps\demo\grails-app\controllers [mkdir] Created dir: D:\_DEV\grails_apps\demo\grails-app\services [mkdir] Created dir: D:\_DEV\grails_apps\demo\grails-app\domain [mkdir] Created dir: D:\_DEV\grails_apps\demo\grails-app\taglib [mkdir] Created dir: D:\_DEV\grails_apps\demo\grails-app\utils [mkdir] Created dir: D:\_DEV\grails_apps\demo\grails-app\views [mkdir] Created dir: D:\_DEV\grails_apps\demo\grails-app\views\layouts [mkdir] Created dir: D:\_DEV\grails_apps\demo\grails-app\i18n [mkdir] Created dir: D:\_DEV\grails_apps\demo\grails-app\conf [mkdir] Created dir: D:\_DEV\grails_apps\demo\test [mkdir] Created dir: D:\_DEV\grails_apps\demo\test\unit [mkdir] Created dir: D:\_DEV\grails_apps\demo\test\integration [mkdir] Created dir: D:\_DEV\grails_apps\demo\scripts [mkdir] Created dir: D:\_DEV\grails_apps\demo\web-app [mkdir] Created dir: D:\_DEV\grails_apps\demo\web-app\js [mkdir] Created dir: D:\_DEV\grails_apps\demo\web-app\css [mkdir] Created dir: D:\_DEV\grails_apps\demo\web-app\images [mkdir] Created dir: D:\_DEV\grails_apps\demo\web-app\WEB-INF\classes [mkdir] Created dir: D:\_DEV\grails_apps\demo\web-app\META-INF [mkdir] Created dir: D:\_DEV\grails_apps\demo\lib [mkdir] Created dir: D:\_DEV\grails_apps\demo\grails-app\conf\spring [mkdir] Created dir: D:\_DEV\grails_apps\demo\grails-app\conf\hibernate[propertyfile] Creating new property file: D:\_DEV\grails_apps\demo\application.properties [copy] Copying 2 files to D:\_DEV\grails_apps\demo [copy] Copying 2 files to D:\_DEV\grails_apps\demo\web-app\WEB-INF [copy] Copying 5 files to D:\_DEV\grails_apps\demo\web-app\WEB-INF\tld [copy] Copying 87 files to D:\_DEV\grails_apps\demo\web-app [copy] Copying 17 files to D:\_DEV\grails_apps\demo\grails-app [copy] Copying 1 file to D:\_DEV\grails_apps\demo [copy] Copying 1 file to D:\_DEV\grails_apps\demo [copy] Copying 1 file to D:\_DEV\grails_apps\demo[propertyfile] Updating property file: D:\_DEV\grails_apps\demo\application.propertiesCreated Grails Application at D:\_DEV\grails_apps/demoD:\_DEV\grails_apps>通過“grails create-app”這個命令,Grails自動幫我們建立了開發所需的工程環境。其實您現在就已經擁有了一個可啟動並執行Web應用程式,然後進入demo目錄(“cd demo”),輸入“grails run-app”,斷行符號,啟動這個‘五髒俱全’的程式雛形,開啟瀏覽器,輸入 http://localhost:8080/demo ,斷行符號,看到了吧 :) 讓我們繼續吧,請停止這個程式(Ctrl + C)4,在“命令列”中輸入“cd demo”,斷行符號,以進入demo目錄,然後再輸入“grails create-domain-class User”建立domain class即類似於pojo的pogo,它對應MVC中的Model,不過由Grails自動建立的pogo是空的,需要自己添加屬性,約束(constraints)等。輸出結果如下所示:D:\_DEV\grails_apps\demo>grails create-domain-class UserWelcome to Grails 1.0 - http://grails.org/Licensed under Apache Standard License 2.0Grails home is set to: D:\D\MY_DEV\grails-1.0Base Directory: D:\_DEV\grails_apps\demoEnvironment set to developmentNote: No plugin scripts foundRunning script D:\D\MY_DEV\grails-1.0\scripts\CreateDomainClass.groovy [copy] Copying 1 file to D:\_DEV\grails_apps\demo\grails-app\domainCreated for User [copy] Copying 1 file to D:\_DEV\grails_apps\demo\test\integrationCreated Tests for UserD:\_DEV\grails_apps\demo>5,進入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)6,在“命令列”中輸入“grails generate-all User”,為User產生所有CRUD操作需要的代碼(如控制器UserController.groovy)和頁面(如list.gsp),輸出結果如下所示:D:\_DEV\grails_apps\demo>grails generate-all UserWelcome to Grails 1.0 - http://grails.org/Licensed under Apache Standard License 2.0Grails home is set to: D:\D\MY_DEV\grails-1.0Base Directory: D:\_DEV\grails_apps\demoEnvironment set to developmentNote: No plugin scripts foundRunning script D:\D\MY_DEV\grails-1.0\scripts\GenerateAll.groovy [mkdir] Created dir: D:\_DEV\grails_apps\demo\web-app\WEB-INF\lib [mkdir] Created dir: C:\Documents and Settings\Daniel\.grails\1.0\projects\demo\classes [groovyc] Compiling 7 source files to C:\Documents and Settings\Daniel\.grails\1.0\projects\demo\classes [mkdir] Created dir: C:\Documents and Settings\Daniel\.grails\1.0\projects\demo\resources\grails-app\i18n[native2ascii] Converting 10 files from D:\_DEV\grails_apps\demo\grails-app\i18n to C:\Documents and Settings\Daniel\.grails\1.0\projects\demo\resources\grails-app\i18n [copy] Copying 1 file to C:\Documents and Settings\Daniel\.grails\1.0\projects\demo\classes [copy] Copying 1 file to C:\Documents and Settings\Daniel\.grails\1.0\projects\demo\resources [copy] Copying 1 file to C:\Documents and Settings\Daniel\.grails\1.0\projects\demo[0] spring.GrailsWebApplicationContext Refreshing org.codehaus.groovy.grails.commons.spring.GrailsWebApplicationContext@2b2057: display name [org.codehaus.groovy.grails.commons.spring.GrailsWebApplicationContext@2b2057]; startup date [Tue Feb 05 23:26:45 CST 2008]; root of context hierarchy[16] spring.GrailsWebApplicationContext Bean factory for application context [org.codehaus.groovy.grails.commons.spring.GrailsWebApplicationContext@2b2057]: org.springframework.beans.factory.support.DefaultListableBeanFactory@eebf17Generating views for domain class User ...Generating controller for domain class User ...Finished generation for domain class UserD:\_DEV\grails_apps\demo>7,修改demo\grails-app\controllers\UserController.groovy的內容為: class UserController { def loginService // 新增的代碼 def index = { redirect(action:list,params:params) } // the delete, save and update actions only accept POST requests def allowedMethods = [delete:'POST', save:'POST', update:'POST'] def list = { if(!params.max) params.max = 10 [ userList: User.list( params ) ] } def show = { def user = User.get( params.id ) if(!user) { flash.message = "User not found with id ${params.id}" redirect(action:list) } else { return [ user : user ] } } def delete = { def user = User.get( params.id ) if(user) { user.delete() flash.message = "User ${params.id} deleted" redirect(action:list) } else { flash.message = "User not found with id ${params.id}" redirect(action:list) } } def edit = { def user = User.get( params.id ) if(!user) { flash.message = "User not found with id ${params.id}" redirect(action:list) } else { return [ user : user ] } } def update = { def user = User.get( params.id ) if(user) { user.properties = params if(!user.hasErrors() && user.save()) { flash.message = "User ${params.id} updated" redirect(action:show,id:user.id) } else { render(view:'edit',model:[user:user]) } } else { flash.message = "User not found with id ${params.id}" redirect(action:edit,id:params.id) } } def create = { def user = new User() user.properties = params return ['user':user] } def save = { def user = new User(params) if(!user.hasErrors() && user.save()) { flash.message = "User ${user.id} created" redirect(action:show,id:user.id) } else { render(view:'create',model:[user:user]) } } // 新增的代碼 def login = { if (request.method == 'POST') { User u = new User() u.properties = params if (!u.validate()) { render(view:'login', model:[user:u]) } 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會自動將其注入到UserController中8,在“命令列”中,輸入“grails create-service Login”,建立LoginService.groovy,輸出:D:\_DEV\grails_apps\demo>grails create-service LoginWelcome to Grails 1.0 - http://grails.org/Licensed under Apache Standard License 2.0Grails home is set to: D:\D\MY_DEV\grails-1.0Base Directory: D:\_DEV\grails_apps\demoEnvironment set to developmentNote: No plugin scripts foundRunning script D:\D\MY_DEV\grails-1.0\scripts\CreateService.groovy [copy] Copying 1 file to D:\_DEV\grails_apps\demo\grails-app\servicesCreated Service for Login [copy] Copying 1 file to D:\_DEV\grails_apps\demo\test\integrationCreated ServiceTests for LoginD:\_DEV\grails_apps\demo>9,修改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 }}10,在demo\grails-app\views\user目錄下建立login.gsp和ok.gsp,它們對應MVC中的View,內容分別為:login.gsp (複製demo\grails-app\views\user\create.gsp的內容到login.gsp中,並修改): Home User List Login ${flash.error}
Name:
Password:
ok.gsp: ${flash.message} Name: ${user?.name}
Password: ${user?.password}11,修改demo\grails-app\conf\BootStrap.groovy,初始化資料庫:將一個User執行個體儲存到資料庫(grails內建hsqldb和jetty)中,內容如下:class BootStrap { def init = { servletContext -> new User(name: "demo", password: "123456").save() } def destroy = { }} 12,在“命令列”中,輸入“grails run-app”,運行我們的Web應用,輸出如下:D:\_DEV\grails_apps\demo>grails run-appWelcome to Grails 1.0 - http://grails.org/Licensed under Apache Standard License 2.0Grails home is set to: D:\D\MY_DEV\grails-1.0Base Directory: D:\_DEV\grails_apps\demoEnvironment set to developmentNote: No plugin scripts foundRunning script D:\D\MY_DEV\grails-1.0\scripts\RunApp.groovy [groovyc] Compiling 4 source files to C:\Documents and Settings\Daniel\.grails\1.0\projects\demo\classesRunning Grails application..2008-02-05 23:46:08.912::INFO: Logging to STDERR via org.mortbay.log.StdErrLog2008-02-05 23:46:08.066::INFO: jetty-6.1.42008-02-05 23:46:08.347::INFO: No Transaction manager found - if your webapp requires one, please configure one.2008-02-05 23:46:09.081:/demo:INFO: Set web app root system property: 'demo' = [D:\_DEV\grails_apps\demo\web-app\]2008-02-05 23:46:09.081:/demo:INFO: Initializing Log4J from [file:C:\Documents and Settings\Daniel/.grails/1.0/projects/demo/resources/log4j.properties]2008-02-05 23:46:09.113:/demo:INFO: Initializing Spring root WebApplicationContext[0] spring.GrailsWebApplicationContext Refreshing org.codehaus.groovy.grails.commons.spring.GrailsWebApplicationContext@5facbd: display name [org.codehaus.groovy.grails.commons.spring.GrailsWebApplicationContext@5facbd]; startup date [Tue Feb 05 23:46:14 CST 2008]; parent: org.springframework.web.context.support.XmlWebApplicationContext@1fef80a[0] spring.GrailsWebApplicationContext Bean factory for application context [org.codehaus.groovy.grails.commons.spring.GrailsWebApplicationContext@5facbd]: org.springframework.beans.factory.support.DefaultListableBeanFactory@aa4c7c2008-02-05 23:46:21.590:/demo:INFO: Initializing Spring FrameworkServlet 'grails'2008-02-05 23:46:21.871::INFO: Started SelectChannelConnector@0.0.0.0:8080Server running. Browse to http://localhost:8080/demo 13,開啟瀏覽器,輸入:http://localhost:8080/demo/user/login ,在Name處輸入demo,Password處輸入123456,點擊‘Login’,跳轉到成功頁面:Welcome demoName: demoPassword: 123456如果您對Grails的工程目錄不太熟悉,我這裡為大家提供了一張表,詳細地描述了各目錄的用途:《Grails權威指南》表3-1.Grails工程目錄目錄名稱相關描述grails-app此目錄包含了Grails應用程式的核心工件(core artifact)+ conf此目錄包含了諸如DevelopmentDataSource.groovy的設定檔+ controllers此目錄包含了處理請求(request)的控制器(controller),Grails控制器將在第7章中進行講解+ domain此目錄包含了領域模型(domain model),領域模型將在第4章進行講解+ i18n此目錄包含了用於國際化的訊息束(message bundle)(譯者註:指的是properties檔案,如messages.properties)+ services此目錄包含了封裝商務邏輯的service檔案,service將在第10章中進行講解+ taglib此目錄包含了輔助頁面產生的動態標籤庫,動態標籤將在第8章中進行講解+ views此目錄包含了Groovy伺服器頁面(GSP)以及JSP頁面+ layouts此目錄包含了GSP或JSP的布局(layout),這些布局由SiteMesh提供支援,這將在第8章中進行講解grails-test此目錄包含了應用程式的單元測試hibernate此目錄包含了可選的Hibernate設定檔,這將在第11章中進行講解lib此目錄包含了jar檔案spring此目錄包含了可選的Spring設定檔,這將在第11章中進行講解src此目錄包含了其他Groovy和Java資源+ java此目錄包含了待編譯的Java源檔案+ groovy此目錄包含了待編譯的Groovy源檔案web-app此目錄包含了Web應用程式的資源(CSS,JavaScript等)註:Grails1.0已將hibernate和spring兩個目錄移到grails-app\conf目錄下了,而grails-test目錄也更名為test,test目錄下有integration目錄和unit目錄,分別存放整合測試代碼和單元測試代碼想象一下用您平時做項目時所用的架構組合(比如SSH)來建立同樣的Web應用程式,您立刻會感受,Grails讓我們專註於商務邏輯,而不用浪費時間在那些scaffolding code(如設定檔)上。從今天開始,您不用再羨慕那些Ruby程式員所用的RoR了,您大可以使用Grails來高效開發Web應用。您也可以訪問Grails官方網站(http://www.grails.org)進一步學習。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.