Grails——下一代web开发框架

Grails——下一代web开发框架

一、 Grails

(一)Why is grails

    Problem we suffer(在web开发的过程中我们遇到的问题):    

    So much time editing configuration files, customizing web.xml files, writing injection definitions, tweaking build scripts, modifying page layouts, restarting apps  on each change .

(在web开发中,我们需要编辑配置文件,配置web.xml文件,写依赖注入,重建脚本,修改页面布局,当修改代码时要重启服务。)

       Grails is a next-generation Java web development framework that generates great  developer productivity gains through theconfluence of a dynamic language, a Convention  over Configuration philosophy, powerfully pragmatic supporting tools, and an agile perspective drawn from the best  emerging web development  paradigms.

(Grails  是下一代java web 开发框架,通过融合动态语言(Groovy),使用约定优于配置的方法,广泛结合务实的支撑工具(插件)。从敏捷的角度看,Grials 是最好的新兴的web 开发框架)

扫描二维码关注公众号,回复: 696307 查看本文章

(二)what  is Grails

Grails是一个full-stack框架,它借助于核心技术与相关的插件(plug-in)来解决Web开发中方方面面的问题,其中包括:

•易于使用的基于Hibernate的对象-关系映射(ORM)层

•称为Groovy Server Pages (GSP)的表现层技术

•基于Spring MVC的控制器层

•构建于Gant 上的命令行脚本运行环境

•内置Tomcat,grails2.0版内置为tomcat7.0

•利用内置的Spring 容器实现依赖注入

•基于Spring的MessageSource核心概念,提供了对国际化(i18n)的支持

•基于Spring事务抽象概念,实现事务服务层

借助于功能强大的Groovy动态语言和领域特定语言(Domain Specific Language,DSL),以上那些特性变得非常易用。

(二)grails feature

(1)convention over configuration  约定优于配置  

(2)Scaffolding 手脚架

(3)Unit Testing 单元测试  

(4)Grails Object Relational Mapping (GORM)

(5)Plug-ins (700多)

二、 Grails环境搭建

安装STS(SpringSource Tools Suite)插件, 再安装grails 和grails support。

安装完后在,STS插件的打开Dashboard窗口,选择Extension窗口,可以在find grails。进行安装grials和grails support

三、 GORM

1.1一对一:

  单向: class Face { Nose nose}  class Nose{}

  双向: class Face{Nose nose}   class Nose{Face face}

  单向级联:class Face{ Nose nose}  class Nose {static belogsTo=[face:Face]}

1.2一对多

class Author {static hasMany = [ books : Book ] String name } 

class Book { String title }

如果你有两个相同类型的属性,他们都是一对多关系的多方,你必须用mappedBy来指定他们分别映射的是哪个集合:

class Airport {

static hasMany = [flights:Flight]

static mappedBy = [flights:"departureAirport"]

}

class Flight {

Airport departureAirport

Airport destinationAirport

}

如果你有多个映射到不同属性的集合,也需要这样:

class Airport {

static hasMany = [outboundFlights:Flight, inboundFlights:Flight]

static mappedBy = [outboundFlights:"departureAirport",inboundFlights:"destinationAirport"]

}

class Flight {

Airport departureAirport

Airport destinationAirport

}

1.3、多对多,只有一方可以管理关联关系。(本例为author)

class Book {

   static belongsTo = Author

   static hasMany = [authors:Author]

   String title

}

class Author {

   static hasMany = [books:Book]

   String name

}

四、MVC

(0)groovy 语言简介

先简单介绍一下groovy 语言: 

Groovy 是 一种JVM 语言,可以无缝隙的使用java的对象和类库 ,直接编译成java字节码。Groovy是运行时编译。 

1、无需用“ ; ”做为语句的结尾。

2、无需setter 和getter。

3、Groovy will compile to bytecode at runtime 。

4、无需引入一些特殊的包。例如:Java.util.*,java.lang.*, java.net.*,      java.io.*, groovy.lang.*, and groovy.util.*. 

5、数组list,set,array,不存在越界,是一种循环数组,

6、数组声明:def  list =[] ; def set = [] as Set ; def string = new  String[3] 

7、数组可以用 .add “要加入的数据” ,加入如数组; 也可以用左进符号,加入  << “要加入的数据”;

8、循环输出: list.each(  println  it) (默认it 为 iterator) 

9、Map 定义 def map =[:];例子:def map =[‘a’:’adc’,’b’:’bbb’];取值       map.a,map.”a”或者,map.get(“a”) 

10、用 ${name} 输出变量 name的值

11、def  list = 0..9 可以循环输出

(1) M:领域类

static  constraints ={ 

  name(maxLength:50,black:false)

   dateOfBirth(nullable:false)

 gender(inList:[“M”,”F”])

 email(maxLength:50,email:true)

}

常见约束类型

(2)C:控制器,默认下,以领域类的名称+controller命名

(1)Scope

•servletContext - Also known as application scope, this scope lets you share state across the entire web application. The servletContext is an instance of ServletContext

•session - The session allows associating state with a given user and typically uses cookies to associate a session with a client. The session object is an instance of HttpSession

•request - The request object allows the storage of objects for the current request only. The request object is an instance of HttpServletRequest

•params - Mutable map of incoming request query string or POST parameters

•flash - Grails supports the concept of flash scope as a temporary store to make attributes available for this request and the next request only. Afterwards the attributes are cleared. This is useful for setting a message directly before redirecting

(2)scoped Controllers

     A、prototype(default) B、session C、singleton

  在controller中用下面的句子即可定义范围

Static scope =”singleton”

(3)V:展示。默认下,在view包下的以领域类命名的包下面的gsp文件。

1、标签库 

使用丰富的GSP标签库,也可以再GSP页面嵌套JSP语言。 

跟JSP一样,GSP也支持自定义标签。 

2、页面布局 

可以创建页面布局Layout文件,丢到views/layouts中即可,后缀还是.gsp。 

3、页面模板 

创建页面Templates,命名规则views/领域类名称/_领域类名称Template.gsp

页面调用: 

<g:render template="bookTemplate" model="[book: myBook]" />

五、Service

(1)事务管理

Grails中可以对service进行事务划分,它声明service中所有方法都是事务型的。缺省所有的service都进行了事务划分。要禁用这个配置,只需要设置transactional 属性为false即可

你需要更细粒度的交易控制或需要指定另类传播级别的时候,Grails也支持Spring的 Transactional注释。

(2)依赖注入:只需在需要注入的domain,controller,service中使用def 

 class AuthorService {

    def bookService

}

六、过滤器

1、要创建一个过滤器,只需要在grails-app/conf目录下创建一个符合规约以Filters结尾的类即可。在此类中,定义一个名为filters的代码块,用以包含过滤器的定义  class ExampleFilters {

   def filters = {

        // your filters here

   }

}

filters代码块内的每一个过滤器有一个名称和作用域。名称就是其方法名,作用域是通过命名参数定义的

sampleFilter(controller:'*', action:'*') {

  // interceptor definitions

}

2、过滤器类型:

•before - 在操作之前执行。返回值false表示响应已经被符合条件的过滤器处理过,并且其操作不被执行

•after - 在操作之后执行。其第一个参数为视图模型(view model),并且允许在渲染视图之前修改此模型

•afterView - 在渲染视图之后执行。如果有异常发生,其第一个参数为一个非null的异常。注意:此闭包在应用布局以前被调用。

class SecurityFilters {

   def filters = {

       loginCheck(controller: '*', action: '*') {

           before = {

              if (!session.user && !actionName.equals('login')) {

                  redirect(action: 'login')

                  return false

               }

           }

       }

   }

}

猜你喜欢

转载自gengqi88.iteye.com/blog/1455679