Groovy语言的学习: Groovy 是用于Java虚拟机的一种敏捷的动态语言,它是一种成熟的面向对象编程语言,既能够用于面向对象编程,又能够用做纯粹的脚本语言。 使用该种语言没必要编写过多的代码,同时又具备闭包和动态语言中的其余特性。 Grails是一套用于快速Web应用开发的开源框架,它基于Groovy编程语言,并构建于Spring、Hibernate等开源框架之上,是一个高生产力一站式框架。 Grails是一个full-stack框架,它借助于核心技术与相关的插件(plug-in)来解决Web开发中方方面面的问题,其中包括: Groovy语言基础知识讲解 易于使用的基于Hibernate的对象-关系映射(ORM)层 使用Groovy Server Pages (GSP)的表现层技术 基于Spring MVC的控制器层 利用内置的Spring 容器实现依赖注入 基于Spring的MessageSource核心概念,提供了对国际化(i18n)的支持 基于Spring事务抽象概念,实现事务服务层。同时借助于功能强大的Groovy动态语言和领域特定语言(Domain Specific Language,DSL),以上那些特性变得很是易用。 下载安装与环境配置: Gralis下载:https:grails.org/ 而后在path中配置 GRAILS_HOME环境变量; 检查:在cmd中 输入:grails 回车,显示黄色字体并出现grails>; 说明配置成功 Groovy下载:http:www.groovy-lang.org/download.html 在path中配置 GROOVY_HOME 环境变量 检查:在cmd中 输入:groovy 回车,出现跟输入java同样的显示。说民配置成功 在cmd中,输入:groovyConsole 回车,等一会 出现了groovyConsole的开发工具,支持动态语言 eclipse中集成groovy的插件方式: 1:检查本身的eclipse版本:在help->About Eclipse中查看 2:进入 https://github.com/groovy/groovy-eclipse/wiki查找和本身eclipse对应版本的groovy 3:拷贝下载地址 4:打开eclipse,在eclipse中,选择help -> Install New Software… 5:选择add,对话框中name随便写,地址将上面拷贝的地址粘贴进去 6:等待会,会出现选项,全选后下一步 7:安装完毕后从新启动eclipse,而后新建项目,选择Other,新建Groovy Project->groovy.class 1.hello world 演示 println " ..hello wrold , hello groovy .." 输出:..hello world , hello groovy.. 2.基本类型与运算符 ㈠groovy 是动态的弱类型语言,声明变量不须要制定类型。变量的类型是根据程序执行的上下文来决定的; def :声明变量类型,相似与 javaScript中的"var" def a = 1; def b = "groovy" def c = true groovy中,单行不须要加";"。而多个语句写在同一行时,须要";"隔开 def a = 1; def b=2 ㈡groovy中的String 输出""与''的区别: 在groovy ""和''均可以使用,用来输出字符串; "" :会输出 ""以内的值,变量转换成具体的值来输出; '' :若是在''中输出了,变量。它会把变量当作表达式来输出 例如: def e = 10 def f = "$e" 输出:10 def h = '$e' 输出:$e ㈢groovy中"""的使用:能够用来输出一个字符段落; 与java中使用"+"拼接的功能相似 def str = """ hello my name is zhangsan my email is zhangsan@126.com """ println str 输出: hello my name is zhangsan my email is zhangsan@126.com ㈣groovy中String的方法 str.size() 字符串的长度 //java.length() str[0..4] 字符串的截取 //java.subString() ㈤groovy中数字 采用精度更高的BigDecimal来进行计算 def a = 1 def b = 2 println a + b //3 println a.plus(b) //3 ㈥groovy中的注释,与java中用法基本一致 单行 // 多行 /** */ ㈦groovy中的类 与java中基本没有什么区 class 前没有限定符,做用域默认 public 缺省default修饰符 构造器基于map初始化 示例: calss A { String name ; int age } def a = new A(name:"zhangsan",age:10) println a.name //a.getName() println a.age //a.getAge() 注:在groovy中,不须要为成员变量添加get/set方法。在运行时,会自动建立 ㈧运算符:groovy中"=="与equals()的使用 在groovy中, 用"=="来比较两个对象的值/内容是否相等 //Java中, "=="用来判断地址值 用".is()" 来比较地址值是否相等/基本类型是否相等 //Java中,".equals()"用来判断值/内容是否相等 ㈨groovy中,assert断言的使用 assert的使用是一种防护性编程;assert()就是一个debug断言 assert(表达式) :若是表达式为假,整个程序会退出,并将输出错误信息; 若是表达式为真,程序继续执行,断言后面的逻辑 3.groovy的控制结构:判断 循环 顺序 ㈠与java的区别: 在java中条件的表达式,只能为boolean值 在groovy中 -->> 传入boolean的使用与java同样 传入数字时, 非0 -->> true; 0 -->> true 传入字符串, null | "" -->> false ; 反之 -->> true 传入集合, .size()->0 -->> false ; .size()>0 -->> true 传入对象, null -->> false ; 反之 -- >> true ㈡for循环结构: for传统风格 ①for( int index = 0; index < 10; index++){ println index } ②for-each风格 for(index in 0..10 ){ println index } ③times风格 10.times{println it} //这里"it" 与java中的 this做用相同 [1,2,3,4,].times{println it } // 打印集合 ㈢switch结构 与java不一样的是,case语句中能够进行多种复杂的判断 实例说明: swith(10){ case 0 : println "0" ;break; // 定值判断 case 0..9 : println "range from 0 to 9 "; break; // 范围判断 case [8,9,11] : println "in 8,9,11";break; // 集合判断 case {it%3==0} :println "multiple";break; // Boolean值判断 default : println "not found ";break; } 4.groovy中的经常使用集合类型 列表:list 映射:map 区间:range ㈠声明 def list = [] //声明一个list集合 def map = [:] //声明一个map集合 def range = 1..5 //声明一个区间 1-5 ㈡list集合的方法及使用 def list = [1,2,3,5,6,7,9,10] list.max() //最大值 list.min() //最小值 list.sum() //求和 list.count(1) //求"1" 出现的次数 list.sort() //从小到大排序 list.size() //求元素个数 list.reverse() //反转 list<<5 //在集合末尾追加元素 5 遍历: for(index in list) { print index + " " } ㈢map结合的方法及使用 def map = [name:"zhangsan",age:21,sex:"male"] map.name //map.get("name") 访问key为name的元素 mep["name"] //同上 map.remove(key)//移除key元素 遍历: --> 使用闭包遍历, 传入自定义参数 data map.each(){ data -> println data.key + ":" + date.value } ㈣range的方法及使用 def range = 1..5 //区间:1-5 def range1 = 1..<5 //区间:1-4 range.size() //元素个数 range.contains(5) //是否包含5元素 5.groovy中的闭包: 闭包是java所不具有的语法结构。闭包就是一个代码块,使用{}括起来。程序代码也成为数据,能够被一个变量所引用。 groovy中的API大量使用闭包,以实现对外开放。 解释:之前程序代码是在编译的时候肯定的,如今程序代码作为一种动态的数据。 ㈠闭包的建立及使用 {参数 -> //若是多个参数用逗号隔开"," 若是省略,能够用"it"的变量访问参数 代码 } 示例: def c = { println it } c.call("hello groovy") c("hello groovy 1") //call能够省略 def c2 = {data -> println data} c2("hello groovy 2") //call能够省略 ㈡闭包的Delegate属性 指定了闭包的代理对,默认状况下delegate与this相同,可是能够手动修改delegate的值,使闭包能够访问其余对象的方法和属性 示例: class Handler{ def method(){ println "handler method called.." } } class Example{ def method(){ println "exmaple method called .." } def foo ( c ){ c.delegate = new Handler() c() } } 输出: new Exmaple().foo(){ method() } //handler method called ㈢采用闭包遍历集合 def list = [1,2,4,5,6] list.each{ print it + " " } def map = [name:"zhangsan",age:10] map.each{ data -> println data.key + ":" + data.value } map.each{ key,value -> println key + ":" + value } 6.groovy中的IO流: ㈠文件的读取 new File("filepath文件存放路径").text() //会自动读取全部的内容 new File("filepath路径").eachLine(){ //采用闭包读取每一行 line -> // 处理代码 } ㈡文件的写入 def out = new File("fielpath文件路径").newPrintWriter() out.write("content内容") //写入内容 out.flush() //把内容数据 刷新到硬盘中 out.close() //关闭流 new File("fielpath文件路径").withPrintWriter(){ out -> out.println("content内容") //采用闭包不须要处理 flush和close } 7.groovy中对json数据的处理 相同的数据内容json的数据占用大小要小于xml格式,特别适合网络传输数据使用; josn数据:{"person":{ "naem":"zhangsan", "sex":"male", "age":10, "hobbies": ["running","baketball","tennis"] } } ㈠JSON读取 import groovy.josn.* def root = new JsonSlurper().parseText(new File("person.json").text() //返回json中的全部内容) // 输出:println root.person.name println root.person.age proot.person.hobbies.each{ print it } ㈡JSON生成 def root = new JsonBuilder() //生成json,使用JsonBuilder这个类,json作为根处理的 root.student{ name "zhangsan" //空格隔开就好 sex "male" age 1 hobbies "runnign","see movie" } println JsonOutput.prettyPrint(root.toString()) //JsonOutput.prettyPrint() 对json的输出进行格式化操做 8.groovy中对数据库的操做 ㈠数据库链接 这里使用的MySQL数据库 def sql = groovy.sql.Sql.newInstance("jdbc:mysql://localhost:3306/student","root","root","com.mysql.jdbc.Driver") println sql.connection //检查链接是成功 ㈡对数据的操做 插入操做: sql.executeInsert("insert into student vlaues(default,?,?)",["zhangsan","male"]) 更新操做: sql.executeUpdate("update student set sex = ? where id = ?)",["femal",3]) 删除数据: sql.execute("delete from student where id = ?",[3]) 查询数据: sql.eachRow("select * from student"){ //使用eachRow的方法,采用闭包访问输出 println it.name + " " + it.sex println "ID:${it.id} Name:${it.name} sex:${it.sex}" //在""里输出变量使用,${变量}来表示 it表示每一行的数据 } 9.groovy中使用GORM操做数据库的CRUD GORM: Grails Object Relational Mapping(对象关系映射) 在底层,它使用hibernate5(流行和灵活的开源ORM解决方案)。但groovy天生动态,实际上对于动态和静态都支持; Grails约定大于配置。只要不多的配置; 像操做对象同样去操做数据库中的数据; ㈠配置数据库各类数据 过程略 ㈡建立对象 class Student{ String name String sex int age } ㈢操做数据 保存数据 def student = new Student(name:"zhangsan",sex:"male",age:12) student.save(flush:true) //把内存的数据刷新到数据库中 ... 读取数据 def student = Student.get(1) //直接读取 参数ID 会当即去数据库查询 def student = Student.load(1) //代理读取 不会当即返回,会返回代理。当去访问代理的字段的时候才去数据库查询 ... 更新数据:grails里没有更新方法 //先查询,而后在更新 def student = Student.get(1) //读取放入二级缓存中 student.name = "KIM" student.save(flush:true) //当去save()时,会去查询二级缓存,若是缓存中有对象,就是更新操做。若是没有数据,就是新增插入数据操做 ... 删除数据 def student = Student.get(1) student.delete(flush:true) ... 查询数据 def list = student.list() list.each{ s -> println s.name } 根据条件查询 def studnets = student.where{ sex == "fale" }.find() students.each{ s -> println s.sex } 10.参考资料 免费学习教程:http://icoolxue.com:1217/album/show/341 钱佳明讲 eclipse插件:http://blog.csdn.net/qq_27645299/article/details/72900801 grails:http://blog.csdn.net/bzray/article/details/5803927