QCon-Grails.ppt
-
Upload
sampetruda -
Category
Documents
-
view
2.023 -
download
4
description
Transcript of QCon-Grails.ppt
Grails: Spring+Hibernate development re-invented Grails = Groovy + Spring + Hibernate
Power and simplicity Productivity and pleasure at last!
By Guillaume Laforge
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
3
Goal of this talk
Learn how to leverage the Groovy web framework Grails to improve developer productivity and code clarity
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
The pains of web development with Java frameworks
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
What’s Grails?
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
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
Pain point one ORM persistence overly hard to master and get right ibatis.xml
hibernate.cfg.xml
persistence.xml
ejb-cmp.xml
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
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
13
Scaffolding to the rescue
Scaffolding is the art of generating parts of the application to get started quickly
Grails scaffolds controllers and views
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 } )
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
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’] )
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()
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
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 ] }}
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
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}
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!" }}
Pain point three Ugly JSPs with scriptlets and the complexity of JSP tags
c.tld
fmt.tld
spring.tld
grails.tld
struts.tld
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
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>
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!
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>
Sweet spot: Enterprise-readiness
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!
Further reading Groovy and Grails books Resources on the Web Grails eXchange 2007 conference Groovy London User Group
31
Groovy and Grails books to go further
Groovy in Action Manning
The Definitive Guide to Grails Apress
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
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
Summary
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
Questions and Answers