Groovy轻松入门——Grails实战基础篇
发布时间:2020-12-14 16:51:30 所属栏目:大数据 来源:网络整理
导读:在学习任何东西之前,最重要的是培养兴趣,Groovy世界最耀眼的技术之一--Grails相信大家早已耳闻,我将通过Grails实战系列文章向您展现Grails的迷人风采,使您感受到Grails的魅力,以至疯狂地爱上Grails,并坠入Groovy的爱河。学Groovy,Grails与学Java一
在学习任何东西之前,最重要的是培养兴趣,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:DMY_DEVgrails)1,设置环境变量GRAILS_HOME(注意大写),过程与“设置环境变量GROOVY_HOME”相似2,将%GRAILS_HOME%bin添加到环境变量path中,过程与“将GROOVY_HOME目录下的bin追加到环境变量path中”相似(如果只想进行Grails开发,可以不设GROOVY_HOME)二,创建Grails Demo程序3,打开“命令行”,选择当前目录(我的为D:Tempgrails_apps),在黑底白字的窗口中输入“grails create-app demo”,不包括双引号“”,在您的屏幕中可以看到类似下面的输出结果:D:_DEVgrails_apps>grails create-app demoWelcome to Grails 1.0 - http://grails.org/Licensed under Apache Standard License 2.0Grails home is set to: D:DMY_DEVgrails-1.0Base Directory: D:_DEVgrails_appsEnvironment set to developmentNote: No plugin scripts foundRunning script D:DMY_DEVgrails-1.0scriptsCreateApp.groovy [mkdir] Created dir: D:_DEVgrails_appsdemosrc [mkdir] Created dir: D:_DEVgrails_appsdemosrcjava [mkdir] Created dir: D:_DEVgrails_appsdemosrcgroovy [mkdir] Created dir: D:_DEVgrails_appsdemograils-app [mkdir] Created dir: D:_DEVgrails_appsdemograils-appcontrollers [mkdir] Created dir: D:_DEVgrails_appsdemograils-appservices [mkdir] Created dir: D:_DEVgrails_appsdemograils-appdomain [mkdir] Created dir: D:_DEVgrails_appsdemograils-apptaglib [mkdir] Created dir: D:_DEVgrails_appsdemograils-apputils [mkdir] Created dir: D:_DEVgrails_appsdemograils-appviews [mkdir] Created dir: D:_DEVgrails_appsdemograils-appviewslayouts [mkdir] Created dir: D:_DEVgrails_appsdemograils-appi18n [mkdir] Created dir: D:_DEVgrails_appsdemograils-appconf [mkdir] Created dir: D:_DEVgrails_appsdemotest [mkdir] Created dir: D:_DEVgrails_appsdemotestunit [mkdir] Created dir: D:_DEVgrails_appsdemotestintegration [mkdir] Created dir: D:_DEVgrails_appsdemoscripts [mkdir] Created dir: D:_DEVgrails_appsdemoweb-app [mkdir] Created dir: D:_DEVgrails_appsdemoweb-appjs [mkdir] Created dir: D:_DEVgrails_appsdemoweb-appcss [mkdir] Created dir: D:_DEVgrails_appsdemoweb-appimages [mkdir] Created dir: D:_DEVgrails_appsdemoweb-appWEB-INFclasses [mkdir] Created dir: D:_DEVgrails_appsdemoweb-appMETA-INF [mkdir] Created dir: D:_DEVgrails_appsdemolib [mkdir] Created dir: D:_DEVgrails_appsdemograils-appconfspring [mkdir] Created dir: D:_DEVgrails_appsdemograils-appconfhibernate[propertyfile] Creating new property file: D:_DEVgrails_appsdemoapplication.properties [copy] Copying 2 files to D:_DEVgrails_appsdemo [copy] Copying 2 files to D:_DEVgrails_appsdemoweb-appWEB-INF [copy] Copying 5 files to D:_DEVgrails_appsdemoweb-appWEB-INFtld [copy] Copying 87 files to D:_DEVgrails_appsdemoweb-app [copy] Copying 17 files to D:_DEVgrails_appsdemograils-app [copy] Copying 1 file to D:_DEVgrails_appsdemo [copy] Copying 1 file to D:_DEVgrails_appsdemo [copy] Copying 1 file to D:_DEVgrails_appsdemo[propertyfile] Updating property file: D:_DEVgrails_appsdemoapplication.propertiesCreated Grails Application at D:_DEVgrails_apps/demoD:_DEVgrails_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:_DEVgrails_appsdemo>grails create-domain-class UserWelcome to Grails 1.0 - http://grails.org/Licensed under Apache Standard License 2.0Grails home is set to: D:DMY_DEVgrails-1.0Base Directory: D:_DEVgrails_appsdemoEnvironment set to developmentNote: No plugin scripts foundRunning script D:DMY_DEVgrails-1.0scriptsCreateDomainClass.groovy [copy] Copying 1 file to D:_DEVgrails_appsdemograils-appdomainCreated for User [copy] Copying 1 file to D:_DEVgrails_appsdemotestintegrationCreated Tests for UserD:_DEVgrails_appsdemo>5,进入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)6,在“命令行”中输入“grails generate-all User”,为User产生所有CRUD操作需要的代码(如控制器UserController.groovy)和页面(如list.gsp),输出结果如下所示:D:_DEVgrails_appsdemo>grails generate-all UserWelcome to Grails 1.0 - http://grails.org/Licensed under Apache Standard License 2.0Grails home is set to: D:DMY_DEVgrails-1.0Base Directory: D:_DEVgrails_appsdemoEnvironment set to developmentNote: No plugin scripts foundRunning script D:DMY_DEVgrails-1.0scriptsGenerateAll.groovy [mkdir] Created dir: D:_DEVgrails_appsdemoweb-appWEB-INFlib [mkdir] Created dir: C:Documents and SettingsDaniel.grails1.0projectsdemoclasses [groovyc] Compiling 7 source files to C:Documents and SettingsDaniel.grails1.0projectsdemoclasses [mkdir] Created dir: C:Documents and SettingsDaniel.grails1.0projectsdemoresourcesgrails-appi18n[native2ascii] Converting 10 files from D:_DEVgrails_appsdemograils-appi18n to C:Documents and SettingsDaniel.grails1.0projectsdemoresourcesgrails-appi18n [copy] Copying 1 file to C:Documents and SettingsDaniel.grails1.0projectsdemoclasses [copy] Copying 1 file to C:Documents and SettingsDaniel.grails1.0projectsdemoresources [copy] Copying 1 file to C:Documents and SettingsDaniel.grails1.0projectsdemo[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:_DEVgrails_appsdemo>7,修改demograils-appcontrollersUserController.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:_DEVgrails_appsdemo>grails create-service LoginWelcome to Grails 1.0 - http://grails.org/Licensed under Apache Standard License 2.0Grails home is set to: D:DMY_DEVgrails-1.0Base Directory: D:_DEVgrails_appsdemoEnvironment set to developmentNote: No plugin scripts foundRunning script D:DMY_DEVgrails-1.0scriptsCreateService.groovy [copy] Copying 1 file to D:_DEVgrails_appsdemograils-appservicesCreated Service for Login [copy] Copying 1 file to D:_DEVgrails_appsdemotestintegrationCreated ServiceTests for LoginD:_DEVgrails_appsdemo>9,修改demograils-appservicesLoginService.groovy的内容为:class LoginService { boolean transactional = true def check(User u) { def user = User.findWhere(name: u.name,password: u.password) return user }}10,在demograils-appviewsuser目录下创建login.gsp和ok.gsp,它们对应MVC中的View,内容分别为:login.gsp (复制demograils-appviewsusercreate.gsp的内容到login.gsp中,并修改):
Login
${flash.error}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |