QCon-Grails.ppt

36
Grails: Spring+Hibernate development re- invented Grails = Groovy + Spring + Hibernate Power and simplicity Productivity and pleasure at last! By Guillaume Laforge

description

 

Transcript of QCon-Grails.ppt

Page 1: QCon-Grails.ppt

Grails: Spring+Hibernate development re-invented Grails = Groovy + Spring + Hibernate

Power and simplicity Productivity and pleasure at last!

By Guillaume Laforge

Page 2: QCon-Grails.ppt

2

About me

Guillaume Laforge

Groovy Project Manager at Codehaus JSR-241 Spec Lead Initiator of the Grails Web framework

Co-author of « Groovy in Action » – Manning

Software Architect at OCTO Technology• A French-based consulting company focusing on

Software Architecture and Agile Methodologies

Page 3: QCon-Grails.ppt

3

Goal of this talk

Learn how to leverage the Groovy web framework Grails to improve developer productivity and code clarity

Page 4: QCon-Grails.ppt

4

Agenda

The pains of web development with Java frameworks What’s Grails? MVC through the pain point prism

Model: transparent Hibernate persistence View: GSP, SiteMesh layouts, dynamic taglibs Controller And Services, Jobs, Ajax…

Sweet spot: Enterprise-readiness Further reading

Page 5: QCon-Grails.ppt

The pains of web development with Java frameworks

Page 6: QCon-Grails.ppt

6

Has it got to be that complex?

Seriously, web development is often painful!

The pain points: ORM persistence overly hard to master and get right Numerous layers and configuration files lead to chaos Ugly JSPs with scriptlets and the complexity of JSP tags

Grails addresses the fundamental flaws in Java web application development today without compromising the platform

Page 7: QCon-Grails.ppt

What’s Grails?

Page 8: QCon-Grails.ppt

8

Grails principles

Grails is an MVC action-based web framework

Principles CoC: Convention over Configuration DRY: Don’t Repeat Yourself

Grails has the essence of frameworks like Ruby on Rails Django, TurboGears

Page 9: QCon-Grails.ppt

9

Grails foundations Grails is built upon solid bricks &

best of breed components

Spring: IoC, DI, Spring MVC, transaction support, etc… Hibernate: ORM, querying mechanism Groovy: for focusing on everything that matters SiteMesh: page layout and composition AJAX libraries: for Web 2.0 user interactivity

Page 10: QCon-Grails.ppt

Pain point one ORM persistence overly hard to master and get right ibatis.xml

hibernate.cfg.xml

persistence.xml

ejb-cmp.xml

Page 11: QCon-Grails.ppt

11

GORM Grails Object Relational Mapping

The domain model is just a set of POGOs(Plain Old Groovy Object)

POGOs are automatically and transparently mapped to the DB on application startup

No more hibernate.cfg.xml!

Grails provides sensible defaults

Page 12: QCon-Grails.ppt

12

Let’s model a small domain

class Book { String title Author author Publisher publisher

def belongsTo = [Publisher, Author]

String toString(){ title }}

class Author { String firstName String lastName

def hasMany = [books: Book] String toString(){ "$firstName $lastName" }}

class Publisher { String name

def hasMany = [books: Book] String toString(){ name }}

Author has many Books Publisher has many Books

Page 13: QCon-Grails.ppt

13

Scaffolding to the rescue

Scaffolding is the art of generating parts of the application to get started quickly

Grails scaffolds controllers and views

Page 14: QCon-Grails.ppt

14

Constraints validationAdd an email to Author

class Author { String email static constraints = { email(email: true)} }

Add an ISBN to Book

class Book { String isbn static constraints = { isbn(matches: "[0-9]{9}[0-9X]")} }

Many constraints available blank, creditcard, email, inList, length, matches, max,

min, nullable, range, size, unique, url, validator

Custom validator even ( validator: { it % 2 == 0 } )

Page 15: QCon-Grails.ppt

15

Querying your model (1/3)

Forget about the boring DAO pattern!

Grails provides various querying mechanisms: Dynamic finder methods Query by example Criteria builders Full-blown HQL queries

Page 16: QCon-Grails.ppt

16

Querying your model (2/3)

Dynamic finder methods Book.findByTitle("The Stand")

Book.findByTitleLike("Harry Pot%") Book.findByReleaseDateBetween(start, end) Book.findByTitleLikeOrReleaseDateLessThan( "%Grails%", someDate)

Find by relationship Book.findAllByAuthor( Author.get(1) )

Affect sorting Book.findAllByAuthor( me, [sort: ‘title’, order: ‘asc’] )

Page 17: QCon-Grails.ppt

17

Querying your model (3/3)

Query by example Book.find ( new Book(title: ‘The Shining’) )

HQL queries Book.find(" from Book b where b.title like ‘Lord of%’ ") Book.find(" from Book b where b.title like ? ", [‘Lord of%’])

Criteria builder def results = Account.createCriteria() {

like("holderFirstName", "Fred%") and { between("balance", 500, 1000) eq("branch", "London") } order("holderLastName", "desc") }.list()

Page 18: QCon-Grails.ppt

Pain point two Numerous layers and configuration files chaos

web.xmlxwork.xml

applicationContext.xml

sitemesh.xml

struts-config.xml

validator.xml

faces-config.xml

tiles.xml

Page 19: QCon-Grails.ppt

19

A sample controllerclass BookController { def index = { redirect(action:list,params:params) }

def list = { [ bookList: Book.list( params ) ] }

def show = { [ book : Book.get( params.id ) ] }

def edit = { def book = Book.get( params.id ) if(!book) { flash.message = "Book ${params.id} not found" redirect(action:list) } else return [ book : book ] }}

Page 20: QCon-Grails.ppt

20

Conventions and handy dynamic

methods URL mapping convention: controller/action/idhttp://localhost:8080/library/book/show/1

Scaffolding can be dynamic (def scaffold = true) static (code generation)

Controllers pass data to the view through simple maps Direct access to parameters Easy redirect and forward with dynamic methods Can define allowed HTTP methods for each action

Page 21: QCon-Grails.ppt

21

Services injected in your controllers

Services are Groovy classes that should contain your business logic

Automatic injection of services in controllers & services simply by declaring a field:

class BookController { MySuperService mySuperService}

Page 22: QCon-Grails.ppt

22

Job scheduling

You can create recuring events with Quartz under the hood, configured by Spring

Again a convention on name and directory Regular intervals, or cron definitions

class MyJob { def cronExpression = "0 0 24 * * ?" def execute() { print "Job run!" }}

Page 23: QCon-Grails.ppt

Pain point three Ugly JSPs with scriptlets and the complexity of JSP tags

c.tld

fmt.tld

spring.tld

grails.tld

struts.tld

Page 24: QCon-Grails.ppt

24

Views Spring MVC under the hood Support for flash scope between requests GSP: Groovy alternative to JSP Dynamic taglib development:

no TLD, no configuration, just conventions Adaptive AJAX tags (Yahoo, Dojo, Prototype) Customisable layout with SiteMesh Page fragments through reusable templates Views under grails-app/views

Page 25: QCon-Grails.ppt

25

GSP: Groovy Server Pages

<html> <head> <meta name="layout" content="main" /> <title>Book List</title> </head> <body> <a href="${createLinkTo(dir:'')}">Home</a> <g:link action="create">New Book</g:link> <g:if test="${flash.message}"> ${flash.message} </g:if> <g:each in="${bookList}">${it.title}</g:each> </body></html>

Page 26: QCon-Grails.ppt

26

Rich set of dynamic taglibs

Logical: if, else, elseif Iterative: while, each, collect, findAll… Linking: link, createLink, createLinkTo Ajax: remoteFunction, remoteLink, formRemote,

submitToRemote… Form: form, select, currencySelect, localeSelect,

datePicker, checkBox… Rendering: render*, layout*, paginate… Validation: eachError, hasError, message UI: richTextEditor…

Many external contributions for new taglibs!

Page 27: QCon-Grails.ppt

27

Write your own taglib and reload it!

Yet another Grails convention:

class MyTagLib { def isAdmin = { attrs, body -> def user = attrs['user'] if(user != null && checkUserPrivs(user)) body() }}

Use it in your GSP:

<g:isAdmin user="${myUser}"> some restricted content</g:isAdmin>

Page 28: QCon-Grails.ppt

Sweet spot: Enterprise-readiness

Page 29: QCon-Grails.ppt

29

Protect your investment

Reuse Existing Java libraries Employee skills & knowledge Spring configured beans Hibernate mappings for legacy schemas

(but still benefit from dynamic finders) EJB3 annotated mapped beans JSPs, taglibs for the view

Deploy on your pricey Java app-server & database

Grails will fit in your JEE enterprise architecture!

Page 30: QCon-Grails.ppt

Further reading Groovy and Grails books Resources on the Web Grails eXchange 2007 conference Groovy London User Group

Page 31: QCon-Grails.ppt

31

Groovy and Grails books to go further

Groovy in Action Manning

The Definitive Guide to Grails Apress

Page 32: QCon-Grails.ppt

32

Groovy and Grails on the Web

Grails eXchange 2007 conference in London http://www.grails-exchange.com

Grails web framework http://grails.org

Groovy dynamic language for the JVM http://groovy.codehaus.org

AboutGroovy news site on Groovy & Grails http://aboutgroovy.com

Getting started with Grails InfoQ book http://www.infoq.com/minibooks/grails

GroovyBlogs javablogs-like agregator built with Grails http://groovyblogs.com

Page 33: QCon-Grails.ppt

33

Grails eXchane conference

Don’t miss the Grails eXchange 2007 conference! 4 tracks

The Groovy Language The Grails framework Ajax and Web 2.0 Java Enterprise Edition

Famous speakers from Interface21, Google, JBoss, Sun Tonight: London Groovy & Grails User Group meeting

18:30 at SkillsMatter HQ

Page 34: QCon-Grails.ppt

Summary

Page 35: QCon-Grails.ppt

35

Summary and beyond! Grails

Lowers the barrier of entry onto the Java platform Brings back both productivity and pleasure of development Lets you build applications in an incremental way Allows you to scale your app in complexity and infrastructure

Only scratched the surface! We haven’t mentionned: Everything can be unit-tested easily, Canoo Web Test integration Flexible plugin architecture to create new artifacts Spring bean builder to script Spring configs Scripting environment (consoles to test your code manually) How we can reuse Java libraries, external mappings, spring confs

Page 36: QCon-Grails.ppt

Questions and Answers