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 demo

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

Base Directory: D:/_DEV/grails_apps
Environment set to development
Note: No plugin scripts found
Running 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.properties
Created Grails Application at D:/_DEV/grails_apps/demo
D:/_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 User

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

Base Directory: D:/_DEV/grails_apps/demo
Environment set to development
Note: No plugin scripts found
Running script D:/D/MY_DEV/grails-1.0/scripts/CreateDomainClass.groovy
     [copy] Copying 1 file to D:/_DEV/grails_apps/demo/grails-app/domain
Created  for User
     [copy] Copying 1 file to D:/_DEV/grails_apps/demo/test/integration
Created Tests for User
D:/_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: 
, 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 User

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

Base Directory: D:/_DEV/grails_apps/demo
Environment set to development
Note: No plugin scripts found
Running 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/re
sources/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 hierarch
y
[16] spring.GrailsWebApplicationContext Bean factory for application context [org.codehaus.groovy.grails.commons.spring.GrailsWebApplicationConte
xt@2b2057]: org.springframework.beans.factory.support.DefaultListableBeanFactory@eebf17
Generating views for domain class User ...
Generating controller for domain class User ...
Finished generation for domain class User
D:/_DEV/grails_apps/demo>


7,修改demo/grails-app/controllers/UserController.groovy的内容为:

            
 UserController {

    def loginService 
//  新增的代码
    
    def index 
 { redirect(action:list,params:params) }

    
 the delete, save and update actions only accept POST requests     def allowedMethods   [delete: ' POST ]

    def list 
 {
        
if ( ! params.max) params.max  =  10
        [ userList: User.list( params ) ]
    }

    def show 
 {
        def user 
 User.get( params.id )

        
user) {
            flash.message 
User not found with id ${params.id}
            redirect(action:list)
        }
        
else  {  return  [ user : user ] }
    }

    def delete 
 User.get( params.id )
        
(user) {
            user.delete()
            flash.message 
User ${params.id} deleted  {
            flash.message 

            redirect(action:list)
        }
    }

    def edit 
 {
            
 [ user : user ]
        }
    }

    def update 
(user) {
            user.properties 
 params
            
user.hasErrors()  &&  user.save()) {
                flash.message 
User ${params.id} updated
                redirect(action:show,id:user.id)
            }
            
 {
                render(view:
edit
            redirect(action:edit,id:params.id)
        }
    }

    def create 
new  User()
        user.properties 
 params
        
 [ user :user]
    }

    def save 
 User(params)
        
 user.save()) {
            flash.message 
User ${user.id} created
            redirect(action:show,id:user.id)
        }
        
 {
            render(view:
create     def login   (request.method  ==  ) {
            User u 
 User()
            u.properties 
 params
    
            
 ( u.validate()) {
                render(view:
login  (params.name   params.password) {
    
                def user 
 loginService.check(u)
                
                
 (user) {
                    flash.message 
Welcome ${user.name}  
                    render(view: 
ok  {
                    flash.error 
Invalid ${u.name} with ${u.password}
                    render(view: 
 {
                render(view: 
8,在“命令行”中,输入“grails create-service Login”,创建LoginService.groovy,输出:

D:/_DEV/grails_apps/demo>grails create-service Login

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

Base Directory: D:/_DEV/grails_apps/demo
Environment set to development
Note: No plugin scripts found
Running script D:/D/MY_DEV/grails-1.0/scripts/CreateService.groovy
     [copy] Copying 1 file to D:/_DEV/grails_apps/demo/grails-app/services
Created Service for Login
     [copy] Copying 1 file to D:/_DEV/grails_apps/demo/test/integration
Created ServiceTests for Login
D:/_DEV/grails_apps/demo>


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

 LoginService {

     boolean  transactional  true

    def check(User u) {
        def user 
 User.findWhere(name: u.name, password: u.password)
        
 user
    }

}


10,在demo/grails-app/views/user目录下创建login.gsp和ok.gsp,它们对应MVC中的View,内容分别为:
login.gsp (复制demo/grails-app/views/user/create.gsp的内容到login.gsp中,并修改):

 



< html >
    
head
        
meta  http-equiv ="Content-Type"  content ="text/html; charset=UTF-8" /> name ="layout" ="main"  <!--  将Create User修改为Login  --> title Login </          
    
body div  class ="nav"
            
span  ="menuButton" >< ="home"  href ="${createLinkTo(dir:'')}" Home a ></ span g:link  ="list"  action ="list" User List g:link div ="body" h1  将flash.message修改为flash.error  g:if  test ="${flash.error}"  将class="message"修改为class="errors", 将flash.message修改为flash.error  ="errors" ${flash.error} g:if g:hasErrors  bean ="${user}"
                
g:renderErrors  ="${user}"  as ="list"  g:hasErrors
            
            
 将action="save"修改为action="login"  g:form  action ="login"  method ="post"  ="dialog"
                    
table
                        
tbody
                        
                            
tr  ="prop"
                                
td  valign ="top"  class ="name"
                                    
label  for Name: label td ="value ${hasErrors(bean:user,field:'name','errors')}" input  type ="text"  id ="name"  name  value ="${fieldValue(bean:user,field:'name')}"
                            
tr  
                        
                            
="password" Password:  maxlength ="16" ="password"  
                        
                        
="buttons"  将value="Create"修改为value="Login"  ="button" ="save"  type ="submit" ="Login"  /></ g:form


ok.gsp:

 

="${flash.message}" ="message" ${flash.message}

Name: ${user?.name}   
br
Password: ${user?.password}


11,修改demo/grails-app/conf/BootStrap.groovy,初始化数据库:将一个User实例保存到数据库(grails自带hsqldb和jetty)中,内容如下:

 BootStrap {

     def init   { servletContext  ->
        
 User(name:  demo 123456 ).save()
     }

     def destroy 
 {
     }


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

D:/_DEV/grails_apps/demo>grails run-app

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

Base Directory: D:/_DEV/grails_apps/demo
Environment set to development
Note: No plugin scripts found
Running 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/classes
Running Grails application..
2008-02-05 23:46:08.912::INFO:  Logging to STDERR via org.mortbay.log.StdErrLog
2008-02-05 23:46:08.066::INFO:  jetty-6.1.4
2008-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.pro
perties]
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.springframew
ork.web.context.support.XmlWebApplicationContext@1fef80a
[0] spring.GrailsWebApplicationContext Bean factory for application context [org.codehaus.groovy.grails.commons.spring.GrailsWebApplicationContex
t@5facbd]: org.springframework.beans.factory.support.DefaultListableBeanFactory@aa4c7c
2008-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:8080
Server running. Browse to http://localhost:8080/demo

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

Welcome demo
Name: demo
Password: 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)进一步学习。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


背景:    8月29日,凌晨4点左右,某服务告警,其中一个节点直接down掉,收到告警的同事让运维重启。    9点左右,内存监控上发现内存异常,堆内存涨速很快,即便GC也没有什么效果,频繁GC。    9点38,服务各种超时,影响整个app使用。处理方式:    当时由于很想要
https://support.smartbear.comeadyapi/docs/soapui/steps/groovy.htmlGettestcaseobjectToobtaintheobjectwhichreferstothecontainingtestcase,usethefollowingcodesnippet:Groovy def case=testRunner.testCase; Byusingthe tes
有几个选项可用于执行自定义JMeter脚本并扩展基线JMeter功能。查看最流行的扩展机制,比较性能并分析哪一个是最好的。  这是乐队之战,JMeter风格。 BeanshellV.JSR223V.JavaRequestSampler 在我们之前的帖子中,  JMeterPerformance和TuningTips  ( 由fantastik
Scala和Java为静态语言,Groovy为动态语言Scala:函数式编程,同时支持面向对象Groovy:jvm上的脚本,较好兼容java语法,Groovy加强了Java集成。 可配置化的优势,可以将一些简单的逻辑公开给外部编辑和使用,增强了互操作性,复杂逻辑来说,可配置化代码的调试则会比较麻烦 Scala和Java
出处:https://www.jianshu.com/p/ce6f8a1f66f4一、一些内部元件的访问testRunner.testCase开头1、向下访问testRunner.testCase.testSteps[testStepName]testRunner.testCase.getTestStepByName("新增一个空间")2、向上访问,用于访问同一项目中的其他testSuites和testCase下
在运行groovy的junit方法时,报了这个错误:java.lang.ExceptionInInitializerError atorg.codehaus.groovy.reflection.ClassInfo.isValidWeakMetaClass(ClassInfo.java:271) atorg.codehaus.groovy.reflection.ClassInfo.getMetaClassForClass(ClassInfo.java:241) atorg.codeha
基本语法1.Grovvy的注释分为//和/**/和java的一样.2.Grovvy语法可以不已分号结尾.3.单引号,里面的内容严格的对应java中的String,不对$符号进行转义.defs1='iamastudent$'printlns1iamastudent$4.双引号“”的内容中如果有$号的话,会先对表达式先求值.de
Tiobe发布了最新一期(3月份)编程语言欢迎度榜单,其榜单根据互联网上有经验的程序员、课程和第三方厂商的数量,并使用搜索引擎(如Google、Bing、Yahoo!)以及Wikipedia、Amazon、YouTube统计出排名数据。TOP5几乎没有变化,Java和C语言牢牢占据前两名。Python相较去年上升一位进入TOP3,C++下
我有一个Google地图组件,作者可以在其中指定纬度和经度.我正在使用带有正则表达式的常规“输入”类型控件来验证它们是否是数字,但是,当试图解决指定范围的问题时(经度验证该值在[-180,180]内并且纬度[-90,90])但是,通过正则表达式进行验证似乎很麻烦,而且利用inputtype=“numb
我正在为未来的应用程序评估SpringBoot,并希望使用Groovy模板来实现其纯粹的可读性.不幸的是,我在迭代我添加到控制器返回的ModelAndView对象的对象列表时遇到了麻烦.这是我的控制器:@RestController@RequestMapping("/ships")publicclassShipsController{@Autowired
我有一个基于Spring的java应用程序,其中包含一些有用的组件.作为系统的一部分,我有一个groovy脚本,来处理一些报告.我想从groovy脚本中调用spring组件.当我用Java编写时,我需要在@Component中使用@Autowired注释,即@ComponentclassReporter{@AutowiredSearchServicesearchS
在Grailsi18n插件definedthusly中定义了一个messageSourcebean:messageSource(PluginAwareResourceBundleMessageSource){basenames=baseNames.toArray()fallbackToSystemLocale=falsepluginManager=manager....}是否可以覆盖我的resources.groovy中的fa
我正在寻找一种方法来反向工程RDBMS表(MSSQLServer)并生成JPA@EntityGroovy类.我们目前没有选择使用Grails和/或GORM,因此Grailsdb-reverse-engineer插件似乎很接近但不太正确.它生成符合GORM的类而不是JPA实体类.我们目前有一个gradle构建,它利用org.hibernate.tool.ant.Hibe
https://blog.csdn.net/Gdeer/article/details/83062523一、直接运行groovy程序因为groovy插件和android插件不兼容,所以不能在原始项目上使用groovy。 新建module,创一个JavaLibrary,取名lib。  修改lib/build.gradleapplyplugin:'java-library'depe
一、自动生成GET请求脚本1、配置Createascript在ngrinder管理台主页,点击script–>Createascript,并填写脚本名称和请求的url,如下所示:点击Create按钮,nGrinder会自动生成对应的脚本结构,如果没有参数需要设置的话,可以直接运行了。二、详细解析GET请求脚本ngrinder自动生成的脚本
我正在关注使用列表和地图作为构造函数的this博文.为什么以下列表无法强制反对?classTest{staticclassTestObject{privateinta=1;protectedintb=2;publicintc=3;intd=4;Strings="s";}stati
Information:java:Errorsoccurredwhilecompilingmodule'security'Information:javac1.8.0_131wasusedtocompilejavasourcesInformation:2019/6/98:31-Buildcompletedwith1errorand0warningsin3s116msError:java:读取E:\repository\org
ngrinder中的groovy脚本结构类似junit,同时在junit的基础之上封装了自己的注解,用来控制脚本的运行。一、运行逻辑图如下:此处只列出了groovy脚本的逻辑,jython脚本是类似的,在此不再单独介绍。二、各注解的使用比较三、关注点在ngrinder中,通常使用单进程多线程就足够大部分测试了,所以:
我有一个switch语句来处理javaenumfoo,并使用spock编写一些groovy单元测试.我已经添加了一个测试,它验证当前是否处理了每种类型的foo而没有抛出异常.现在我想测试一个无法识别的foo类型会导致抛出异常.要做到这一点,我将不得不嘲笑枚举,并已经看到这里概述的解决方案:MockingJ
我有一个groovy实体ClientInvoiceAttachmentExt,它扩展了java实体ClientInvoiceAttachment.ClientInvoiceAttachment具有@Id注释,但仍然看到“没有为实体指定的标识符”错误这是我的堆栈跟踪[Mar0317:11:54]ERROR|org.springframework.web.context.ContextLoader|Contex