Top Banner
[email protected] Introduction to Grails Framework Introduction to Grails Framework Miguel Ping 18/03/2010
27

Introduction to Grails Framework

Sep 01, 2014

Download

Technology

PT.JUG

Apresentação de Miguel Ping - 5º encontro PT.JUG.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

Introduction to Grails Framework Miguel Ping18/03/2010

Page 2: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

• Small Introduction on Groovy

• Grails• Grails = Groovy on (G)Rails

• Grails is MVC• Powered by Spring and Hibernate• Model/Domain Layer• View Layer• Controllers

• Demo

Agenda

Page 3: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

Groovy

+ =

Page 4: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

Java Class

public class HelloWorld { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } public String greet() { return "Hello " + name; } public static void main(String[] args) { HelloWorld helloWorld = new HelloWorld(); helloWorld.setName("Groovy"); System.out.println(helloWorld.greet()); }}

Page 5: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

Groovy Class

public class HelloWorld { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } public String greet() { return "Hello " + name; } public static void main(String[] args) { HelloWorld helloWorld = new HelloWorld(); helloWorld.setName("Groovy"); System.out.println(helloWorld.greet()); }}

Page 6: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

• Multiple classes per file, or even no classes at all (scripts)

• Public unless defined otherwise

• Getters and Setters by default

• String interpolation

• Semicolons are optional

• Type declarations are optional

• Return keyword is optional

Groovy Features

class HelloWorld { def name def greet() { "Hello ${name}" }}

helloWorld = new HelloWorld(name: "Groovy")println helloWorld.greet()

Page 7: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

• Dynamic language (everything happens at runtime)

• Dynamically typed (types are “optional”)

• Closures• Anonymous Inner Classes (recently)

• Meta Object Protocol• Hence, MetaClasses and all the magic

• Compiles down to bytecode

• Excellent Java Interop (Groovy can call Java and vice-versa)

• Lots of synthatic sugar• person?.address

• def a = b ?: c

Groovy Definition

Page 8: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

Grails

+ =

Page 9: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

• Spring framework released in 2003

• SpringSource founded in 2004

• G2One (The Groovy Grails Company) founded in 2007 by the Groovy and Grails project leads

• November 2008: G2One was acquired by SpringSource

• August 2009: SpringSource was acquired by VMware for $420m

• SpringSource is now a division of VMware

Overview

Page 10: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

• Grails is Groovy + Spring + Hibernate + Some nice stuff

• Heavily inspired on Rails framework• But takes advantage of Java technology like Spring and servlets

• It means good Java (platform) integration

• Produces .war artifacts deployable in any servlet container

• Has some command-line scripts to ease the pain• > grails generate-all MyClass• > grails test-app -integration

• Has a plugin architecture• > grails install-plugin jquery

Overview

Page 11: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

Grails is a Full Stack

Groovy

Java Virtual Machine / JDK

Spring

Hibernate Other Libraries

Grails

SitemeshPlugins

Page 12: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

Application structure

• grails-app Top level source folder with Grails artifacts

• conf Configuration sources

• controlllers Controller layer

• domain Model layer

• i18n Internationalized Resource Bundles

• services Service layer

• taglib Dynamic Tag Libraries

• views Groovy Server Pages (GSP)

• web-app Stylesheets, Javascript, etc

• scripts Custom command-line scripts

• src Other project sources

• groovy Other Groovy project sources

• java Other Java project sources

• lib 3th Party Libraries

• test Unit, Integration and Functional tests

Page 13: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

• POGO – Plain Old Groovy Objects• Plus a DSL for domain constraints

• Constraints/Validations• relationships

• belongsTo, hasMany, mappedBy

• max, min, blank, nullable, ... , custom• Implies validation

• hasErrors(), validate()

• DB operations • CRUD: save(), delete(), ...

• Dynamic Finders• FindAllBy<Field> - Magick!!!

Models

Page 14: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

Example of a Model

• class Book { static belongsTo = [author: Author] //no ID declaration String title String isbn BigDecimal price Date dateCreated Date lastUpdated //Callbacks def beforeInsert() { dateCreated = new Date() //not really necessary } // DSL for constraints static constraints = { title(blank: false, maxSize: 100) isbn(blank: false, matches: "[0-9]{13}", minSize: 13, maxSize: 13, unique: true) price(nullable: true, min: 0.0, max: 9999.99, scale: 2) } // DSL for database mapping static mapping = { table "books" price column: "sales_price" }}

Page 15: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

• A lot like JSPs

• Taglib• Pagination, i18n, ajax, page navigation

• Hyperlinks• <g:link controller=“<controller>” action=“<action>”

params=“<params>”>• Controller is the controller name• Action is the closure name• Params are available in the controller’s closure

• etc (including custom taglibs)

• Partial render/Templates• Reusable, allows composition

• g:render

• Layouts

Views - GSPs

Page 16: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

Views - Taglibs

• Logic and Iteration <g:if> <g:else> <g:elsif> <g:each> <g:while>

• Links and Resources <g:link action="show" id="${currentBook.id}">$

{currentBook.name}</g:link><g:link controller="book" action="list">Book List</g:link>

• Forms and Fields<g:textField name="title" value="${bookInstance.title}" /><g:select name="author.id" from="${Author.list()}" value="$

{book.author.id}" /><g:datePicker name="publishDate" value="$

{bookInstance.publishDate}" />

• Do Your Own

class SimpleTagLib { static namespace = "auth" def isAdmin = { attrs, body -> if (attrs.user.admin) out << body() }}

<auth:isAdmin user="${session.user}"> // some restricted content</auth:isAdmin>

Page 17: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

Example of a GSP

• Embedded Groovy code<html> <body> <% [1, 2, 3, 4].each { num -> if (num > 2) { %> <p><%= "Hello ${num}!" %></p> <% } } %> </body></html>

• With Tag Libraries<html> <body> <g:each in="${[1, 2, 3, 4]}" var="num"> <g:if test="${num > 2}"> <p>Number ${num}</p> </g:if> </g:each> </body></html>

Page 18: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

• Handle the web request• Grails is action-first, it means the controller runs

before the view

• Spring-managed beans• Can hook up with another beans through Spring DI

• Idiom• params variable

• holds request parameters

• render

• redirect,

• return [beanName: bean]• returns some data to the view

Controllers

Page 19: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

Example of a Controller

• class BookController { //will match http://myApp:8080/book/

static allowedMethods = [save: "POST", update: "POST", delete: "POST"] // default action def index = { redirect(action: "list", params: params) }

def list = {//by default, we go to the “list.gsp” [bookInstanceList: Book.list(params), bookInstanceTotal: Book.count()] }

def edit = { //params is a Map with an ‘id’ key def bookInstance = Book.get(params.id) return [bookInstance: bookInstance] }

def save = { def bookInstance = new Book(params) if (bookInstance.save()) { redirect(action: "show", id: bookInstance.id) } else { render(view: "create", model: [bookInstance: bookInstance]) } }

Page 20: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

• Spring glues everything

• Spring IoC / DI• We can write custom beans and

wire everything together

• Spring MVC

• Spring Transactions

• Spring i18n

Spring Glue

Page 21: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

• Lots and lots of them• Spring Security / Acegi

• RIA/AJAX: RichUI & GrailsUI

• Testing (eg: Canoo, EasyB, etc)

• Debugging plugins (eg: simple dashboard)

• Optimization plugins (eg: js minifier)

• Deployment plugins (eg: google-app-engine, amazon)

• Other • Multi-tenant• Paypal• Openid• SpringWS• GWT

Plugins

Page 22: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

• 2 classes• Constraints

• Relations

• Scaffolding

• Dynamic Finders

• View• Some GSP navigation

• Controllers• CRUD

• AJAX

Test Drive

Page 23: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

Questions

Page 24: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

• grails create-app [app name]

• grails create-controller [controller name]

• grails create-domain-class [class name]

• grails create-service [service name]

• grails create-unit-test [test name]

• grails create-tag-lib [taglib name]

• grails generate-all [class name]

• grails generate-views [class name]

Command line scripts - development

Page 25: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

• grails clean

• grails compile

• grails console

• grails doc

• grails install-plugin

• grails run-app

• grails war

Command line scripts - lifecycle

Page 26: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

• conf/DataSource.groovy• Database connections

• conf/UrlMapping.groovy• Routing

• conf/BootStrap.groovy• Bootstrap file

• conf/Config.groovy• Configurations (MIME mappings, more…)

Important Files

Page 27: Introduction to Grails Framework

[email protected]

Introduction to Grails Framework

• LessThan

• LessThanEquals

• GreaterThan

• GreaterThanEquals

• Between

• Like

• Ilike (i.e. ignorecase like)

• IsNotNull

• IsNull

• Not

• Equal

• NotEqual

• And

• Or

Dynamic Finders