Date post: | 01-Sep-2014 |
Category: |
Technology |
Upload: | ptjug |
View: | 3,841 times |
Download: | 4 times |
Introduction to Grails Framework
Introduction to Grails Framework Miguel Ping18/03/2010
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
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()); }}
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()); }}
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()
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
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
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
Introduction to Grails Framework
Grails is a Full Stack
Groovy
Java Virtual Machine / JDK
Spring
Hibernate Other Libraries
Grails
SitemeshPlugins
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
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
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" }}
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
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>
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>
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
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]) } }
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
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
Introduction to Grails Framework
• 2 classes• Constraints
• Relations
• Scaffolding
• Dynamic Finders
• View• Some GSP navigation
• Controllers• CRUD
• AJAX
Test Drive
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
Introduction to Grails Framework
• grails clean
• grails compile
• grails console
• grails doc
• grails install-plugin
• grails run-app
• grails war
Command line scripts - lifecycle
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
Introduction to Grails Framework
• LessThan
• LessThanEquals
• GreaterThan
• GreaterThanEquals
• Between
• Like
• Ilike (i.e. ignorecase like)
• IsNotNull
• IsNull
• Not
• Equal
• NotEqual
• And
• Or
Dynamic Finders