SlideShare a Scribd company logo
Grails Web app development  with pleasure! Guillaume Laforge Vice-President, Technology G2One, Inc. http://www.g2one.com
Goal of This Talk  Discovering the Grails web framework Learn more about Grails, how easily you can use it in your projects, and how to get back the pleasure of web development!
Guillaume Laforge Groovy Project Manager JSR-241 Spec Lead Initiator of the  Grails  framework Co-author of  Groovy in Action By Dierk König, et al. Vice-President Technology
Agenda What’s Grails? The Problem with the usual web frameworks The different layers Other cool features The plugin system Summary Q&A
What’s Grails? From 10,000 feet From 1,000 feet Near the ground
What’s Grails? (1/3) From 10,000 feet Grails is an  MVC action-based framework Principles CoC : Convention over Configuration DRY : Don’t Repeat Yourself The essence of Ruby on Rails, but with the tight integration with the Java ecosystem Protect your investment!
What’s Grails? (2/3) From 1,000 feet = + +
What’s Grails? (3/3) Near the ground… Grails is built on  proven & solid OSS bricks Spring : IoC, DI, Spring MVC, transactions… Hibernate : ORM, querying mechanism Groovy : for everything that matters SiteMesh : page layout and composition Quartz : for job scheduling AJAX : integration with different libraries Jetty  &  HSQLDB : for fast development cycles
The Grails Stack
Why Groovy? Java-like syntax Flat learning curve The same programming models Same OO, security, threading models The same libraries JDK, and any in-house or OSS JAR And Groovy has… Closures, properties, malleable syntax for DSLs
The Problem What’s the problem with Web frameworks? Why has it got to be complex? What are the pain points?
Has it got to be complex? But it’s slow to start with Seting up the project takes time It gets complicated pretty rapidly Dive into Spring & Hibernate to wire everything together There are so many layers DAOs, DTOs, more abstraction layers Too many configuration files Often too much XML for everything Struts / Spring / Hibernate is okay…
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
The Different Layers Bottom-up!  Transparent persistence Controllers and services Groovy Server Pages, templates & taglibs
Grails’ MVC at a Glance… Model GORM: Grails Object Relational Mapping Controller Multi-action controller Also the Service layer & Quartz job scheduling View GSP: Groovy Server Pages Tag libraries
Pain Point #1 – Peristence ORM is quite hard to master and get right Many configuration files ibatis.xml hibernate.cfg.xml persistence.xml ejb-cmp.xml
GORM – Grails Object Relational Mapping Hibernate under the hood Domain model is a set of POGOs Plain Old Groovy Objects POGOs are transparently mapped! No hibernate.cfg.xml But can be overriden if needed All domain classes get useful instance and static methods for free Book.count(), Book.list(), Book.get(id)… book.save(), book.delete(), book.update()…
Example Grails provides a default ORM mapping strategy for Hibernate // A Book domain class class  Book { String title Date releaseDate static  belongsTo = [author: Author] } // A one-to-many class  User { String name static  hasMany = [bookmarks: Bookmark] } 18 8 Dec 2007 Groovy Recipes 17 2 11 Dec 2006 Groovy in Action 16 author_id release_date title id Dierk König 2 name id
<DEMO/>
Constraints Constraints are added in domain classes through a static  constraint  field: static constraint = {   isbn(matches: &quot;[0-9]{9}[0-9X]&quot;)   } Many constraints available: blank, creditcard, email, blank, nullable, matches, range, unique, url… You can create your own validator myField(validator: { it % 2 == 0 })
No more DAOs! Dynamic finder methods Book. findBy Title (&quot;The Stand&quot;)  Book.findBy Title Like (&quot;Harry Pot%&quot;)  Book.findBy ReleaseDate Between (start, end)  Book.findBy Title LikeOr ReleaseDate LessThan (   &quot;%Grails%&quot;, someDate) Find by relationship Book.findAllByAuthor( Author.get(1) ) Affect sorting Book.findAllByAuthor( me, [sort: ‘title’, order: ‘asc’ ] )
Querying Query by example Book.find ( new Book(title: ‘The Shining’) ) HQL queries Book.find( &quot;  from Book b where b.title like ‘Lord of%’  &quot; ) Book.find( &quot;  from Book b where b.title like ?  &quot;, [ ‘Lord of%’ ] ) Criteria builder def results = Account.createCriteria() {    like (&quot;holderFirstName&quot;, &quot;Fred%&quot;)    and  {    between (&quot;balance&quot;, 500, 1000)   eq (&quot;branch&quot;, &quot;London&quot;)    }   order (&quot;holderLastName&quot;, &quot;desc&quot;)  }.list()
Pain Point #2 – Services, Nav. & Pres. Logic Numerous layers Conf file chaos web.xml xwork.xml applicationContext.xml sitemesh.xml struts-config.xml validator.xml faces-config.xml tiles.xml
Controllers class  Book Controller { 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 = &quot;Book ${params.id} not found&quot; redirect(action:list) } else return [ book : book ] } } http://localhost:8080/myapp/ book / show
Services & Scheduled Tasks 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 } Recuring events (Quartz)  Intervals, or cron definitions class MyJob {    def  cronExpression = &quot;0 0 24 * * ?&quot;   def execute() {    print &quot;Job run!&quot;    } }
Pain Point #3 – The View Layer JSP cluttered with scriptlets Taglibs are painful c.tld fmt.tld spring.tld grails.tld struts.tld
The view layer 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
Groovy Server Pages <html> <head> <meta name=&quot;layout&quot; content=&quot;main&quot; /> <title>Book List</title> </head> <body> <a href=&quot; ${createLinkTo(dir:'')} &quot;>Home</a> <g:link action=&quot;create&quot;> New Book</g:link> <g:if test=&quot;${flash.message}&quot;> ${flash.message} </g:if> <g:each in=&quot; ${bookList} &quot;> ${it.title} </g:each> </body> </html>
Dynamic Tag Libraries 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…
Write your Own Taglib Yet another Grails convention class My TagLib  {   def isAdmin = {  attrs ,  body  ->    def user = attrs['user']    if(user != null && checkUserPrivs(user))   body()     } } Use it in your GSP <g:isAdmin user=&quot;${myUser}&quot;>   some restricted content </g:isAdmin>
What else? Custom URL mapping Conversation flows ORM DSL http://grails.org/GORM+-+ Mapping +DSL Develop with pleasure with IntelliJ IDEA http:// grails.org /IDEA+ Integration
Custom URL Mappings (1/2) Pretty URLs in seconds Custom DSL for mapping URLs to controllers, actions and views Supports mapping URLs to actions  via HTTP methods for REST Supports rich constraints mechanism
Custom URL Mappings (2/2) Pretty URLs in seconds! class UrlMappings {   static mappings = {   &quot;/product/ $id &quot;(controller: &quot;product&quot;,   action: &quot;show&quot;)   &quot;/$blog/ $year? /$month?/$day?&quot;(controller: &quot;blog&quot;,    action: &quot;show&quot;) {   constraints {   year(matches: /\d{4}/)   }   } }
Conversations flows (1/2) Leverages Spring WebFlow Supports Spring’s scopes Request Session Conversation Flash Possibly to specify services’ scope DSL for constructing flows
Conversations flows (2/2) Example: def searchFlow = {   displaySearchForm  {   on(&quot;submit&quot;).to &quot;executeSearch&quot;     }   executeSearch  {   action {   [results: searchService.   executeSearch(params.q)]   }   on(&quot;success&quot;).to &quot;displayResults&quot;   on(&quot;error&quot;).to &quot;displaySearchForm&quot;    }   displayResults() }
Grails plugin system Beyond the out-of-the-box experience, extend Grails with plugins and write your own!
Plugin Extension Points Extend Grails  beyond  what it offers! What can you do with plugins? Hook into the build system Script the Spring application context Register new dynamic methods Container configuration (web.xml) Adding new artefacts types Auto-reload your artefacts
Plenty of Plugins! XFire Expose Grails services as SOAP Searchable Integrate Lucene & Compass search Remoting Expose Grails services over RMI, Burlap, or REST Google Web Toolkit Integrate Grails with GWT for the presentation layer Acegi / JSecurity Secure your Grails app JMS Expose services as message-driven beans
Sweet spot: Enterprise-readiness Skills, libraries, app servers…
Protect your Investment Reuse Existing Java libraries (JDK, 3rd party, in-house) Employee skills & knowledge  (both prod & soft) 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 Java EE enterprise architecture!
Let’s Wrap Up Summary Resources Q&A
Summary Groovy is a  powerful dynamic language  for the JVM, that provides agile development on the Java platform, without the impedance mismatch of other languages    Groovy 1.1 out next week Grails is a fully-featured  web application framework  based on proven technologies like  Spring  and  Hibernate , which simplifies the development of innovative applications    Grails 1.0 at the end of the month
Resources Grails:  http://grails.org Groovy:  http://groovy.codehaus.org Groovy blogs:  http://groovyblogs.org AboutGroovy:  http://aboutgroovy.com Mailing-lists:  http://grails.org/Mailing+lists G2One:  http://www.g2one.com
G2One, Inc. Groovy & Grails at the source! Graeme Rocher, Grails lead Guillaume Laforge, Groovy lead Plus key committers Professional Services Training, support, consulting Custom developments Connectors, plugins, etc…
Q&A

More Related Content

What's hot (19)

PDF
Opening up the Social Web - Standards that are bridging the Islands
Bastian Hofmann
 
PDF
Bringing Typography to the Web with sIFR 3 at <head>
Mark Wubben
 
KEY
Web Typography with sIFR 3 at Drupalcamp Copenhagen
Mark Wubben
 
PPT
Eugene Andruszczenko: jQuery
Refresh Events
 
PPT
Joseph-Smarr-Plaxo-OSCON-2006
guestfbf1e1
 
PPT
Plaxo OSCON 2006
gueste8e0fb
 
PDF
Browser Extensions for Web Hackers
Mark Wubben
 
PPT
JavaScript Workshop
Pamela Fox
 
PDF
Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
Leonardo Balter
 
PPSX
Introduction to Html5
www.netgains.org
 
ODP
Ruby on Rails
Aizat Faiz
 
PDF
HTML5 & Friends
Remy Sharp
 
PPTX
Fronteers 20091105 (1)
guestbf04d7
 
KEY
The Cascade, Grids, Headings, and Selectors from an OOCSS Perspective, Ajax ...
Nicole Sullivan
 
PDF
Web Components and Modular CSS
Andrew Rota
 
PPT
Ajax
wangjiaz
 
PDF
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Nicholas Zakas
 
PPTX
Maintainable JavaScript 2012
Nicholas Zakas
 
PDF
HTML5 Semantics, Accessibility & Forms [Carsonified HTML5 Online Conference]
Aaron Gustafson
 
Opening up the Social Web - Standards that are bridging the Islands
Bastian Hofmann
 
Bringing Typography to the Web with sIFR 3 at <head>
Mark Wubben
 
Web Typography with sIFR 3 at Drupalcamp Copenhagen
Mark Wubben
 
Eugene Andruszczenko: jQuery
Refresh Events
 
Joseph-Smarr-Plaxo-OSCON-2006
guestfbf1e1
 
Plaxo OSCON 2006
gueste8e0fb
 
Browser Extensions for Web Hackers
Mark Wubben
 
JavaScript Workshop
Pamela Fox
 
Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
Leonardo Balter
 
Introduction to Html5
www.netgains.org
 
Ruby on Rails
Aizat Faiz
 
HTML5 & Friends
Remy Sharp
 
Fronteers 20091105 (1)
guestbf04d7
 
The Cascade, Grids, Headings, and Selectors from an OOCSS Perspective, Ajax ...
Nicole Sullivan
 
Web Components and Modular CSS
Andrew Rota
 
Ajax
wangjiaz
 
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Nicholas Zakas
 
Maintainable JavaScript 2012
Nicholas Zakas
 
HTML5 Semantics, Accessibility & Forms [Carsonified HTML5 Online Conference]
Aaron Gustafson
 

Similar to Grails Introduction - IJTC 2007 (20)

PPTX
Introduction to Grails Framework
PT.JUG
 
ODP
Grails 0.3-SNAPSHOT Presentation WJAX 2006 English
Sven Haiges
 
PPT
JavaOne 2008 - TS-5764 - Grails in Depth
Guillaume Laforge
 
ODP
Agile web development Groovy Grails with Netbeans
Carol McDonald
 
PDF
Grails
Gabriel Dogaru
 
PPT
Introduction To Grails
Christopher Bartling
 
POT
intoduction to Grails Framework
Harshdeep Kaur
 
PPTX
Introduction to Grails 2013
Gavin Hogan
 
ODP
SVCC Intro to Grails
James Williams
 
PDF
Grails 101
David Jacobs
 
PDF
Groovy - Grails as a modern scripting language for Web applications
IndicThreads
 
PPT
Introduction To Groovy 2005
Tugdual Grall
 
PDF
Grails @ Java User Group Silicon Valley
Sven Haiges
 
PDF
Grails Launchpad - From Ground Zero to Orbit
Zachary Klein
 
PDF
Naked Objects and Groovy Grails
David Parsons
 
PPT
Fast web development using groovy on grails
Anshuman Biswal
 
ODP
Groovygrailsnetbeans 12517452668498-phpapp03
Kevin Juma
 
PPTX
Grails Advanced
Saurabh Dixit
 
PPT
Groovy & Grails: Scripting for Modern Web Applications
rohitnayak
 
KEY
Introduction To Grails
Eric Berry
 
Introduction to Grails Framework
PT.JUG
 
Grails 0.3-SNAPSHOT Presentation WJAX 2006 English
Sven Haiges
 
JavaOne 2008 - TS-5764 - Grails in Depth
Guillaume Laforge
 
Agile web development Groovy Grails with Netbeans
Carol McDonald
 
Introduction To Grails
Christopher Bartling
 
intoduction to Grails Framework
Harshdeep Kaur
 
Introduction to Grails 2013
Gavin Hogan
 
SVCC Intro to Grails
James Williams
 
Grails 101
David Jacobs
 
Groovy - Grails as a modern scripting language for Web applications
IndicThreads
 
Introduction To Groovy 2005
Tugdual Grall
 
Grails @ Java User Group Silicon Valley
Sven Haiges
 
Grails Launchpad - From Ground Zero to Orbit
Zachary Klein
 
Naked Objects and Groovy Grails
David Parsons
 
Fast web development using groovy on grails
Anshuman Biswal
 
Groovygrailsnetbeans 12517452668498-phpapp03
Kevin Juma
 
Grails Advanced
Saurabh Dixit
 
Groovy & Grails: Scripting for Modern Web Applications
rohitnayak
 
Introduction To Grails
Eric Berry
 
Ad

More from Guillaume Laforge (20)

PDF
Lift off with Groovy 2 at JavaOne 2013
Guillaume Laforge
 
PDF
Groovy workshop à Mix-IT 2013
Guillaume Laforge
 
PDF
Les nouveautés de Groovy 2 -- Mix-IT 2013
Guillaume Laforge
 
PDF
Groovy 2 and beyond
Guillaume Laforge
 
PDF
Groovy 2.0 update at Devoxx 2012
Guillaume Laforge
 
PDF
Groovy 2.0 webinar
Guillaume Laforge
 
PDF
Groovy Domain Specific Languages - SpringOne2GX 2012
Guillaume Laforge
 
PDF
Groovy update at SpringOne2GX 2012
Guillaume Laforge
 
KEY
JavaOne 2012 Groovy update
Guillaume Laforge
 
PDF
Groovy 1.8 et 2.0 au BreizhC@mp 2012
Guillaume Laforge
 
PDF
Groovy 1.8 and 2.0 at GR8Conf Europe 2012
Guillaume Laforge
 
PDF
Groovy 2.0 update - Cloud Foundry Open Tour Moscow - Guillaume Laforge
Guillaume Laforge
 
PDF
Going to Mars with Groovy Domain-Specific Languages
Guillaume Laforge
 
PDF
Groovy 2.0 - Devoxx France 2012
Guillaume Laforge
 
PDF
Whats new in Groovy 2.0?
Guillaume Laforge
 
KEY
Groovy Update, new in 1.8 and beyond - Guillaume Laforge - Devoxx 2011
Guillaume Laforge
 
PDF
GPars et PrettyTime - Paris JUG 2011 - Guillaume Laforge
Guillaume Laforge
 
PDF
Groovy Update - Guillaume Laforge - Greach 2011
Guillaume Laforge
 
KEY
Gaelyk update - Guillaume Laforge - SpringOne2GX 2011
Guillaume Laforge
 
KEY
Groovy Update, what's new in Groovy 1.8 and beyond - Guillaume Laforge - Spri...
Guillaume Laforge
 
Lift off with Groovy 2 at JavaOne 2013
Guillaume Laforge
 
Groovy workshop à Mix-IT 2013
Guillaume Laforge
 
Les nouveautés de Groovy 2 -- Mix-IT 2013
Guillaume Laforge
 
Groovy 2 and beyond
Guillaume Laforge
 
Groovy 2.0 update at Devoxx 2012
Guillaume Laforge
 
Groovy 2.0 webinar
Guillaume Laforge
 
Groovy Domain Specific Languages - SpringOne2GX 2012
Guillaume Laforge
 
Groovy update at SpringOne2GX 2012
Guillaume Laforge
 
JavaOne 2012 Groovy update
Guillaume Laforge
 
Groovy 1.8 et 2.0 au BreizhC@mp 2012
Guillaume Laforge
 
Groovy 1.8 and 2.0 at GR8Conf Europe 2012
Guillaume Laforge
 
Groovy 2.0 update - Cloud Foundry Open Tour Moscow - Guillaume Laforge
Guillaume Laforge
 
Going to Mars with Groovy Domain-Specific Languages
Guillaume Laforge
 
Groovy 2.0 - Devoxx France 2012
Guillaume Laforge
 
Whats new in Groovy 2.0?
Guillaume Laforge
 
Groovy Update, new in 1.8 and beyond - Guillaume Laforge - Devoxx 2011
Guillaume Laforge
 
GPars et PrettyTime - Paris JUG 2011 - Guillaume Laforge
Guillaume Laforge
 
Groovy Update - Guillaume Laforge - Greach 2011
Guillaume Laforge
 
Gaelyk update - Guillaume Laforge - SpringOne2GX 2011
Guillaume Laforge
 
Groovy Update, what's new in Groovy 1.8 and beyond - Guillaume Laforge - Spri...
Guillaume Laforge
 
Ad

Recently uploaded (20)

PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 

Grails Introduction - IJTC 2007

  • 1. Grails Web app development with pleasure! Guillaume Laforge Vice-President, Technology G2One, Inc. http://www.g2one.com
  • 2. Goal of This Talk Discovering the Grails web framework Learn more about Grails, how easily you can use it in your projects, and how to get back the pleasure of web development!
  • 3. Guillaume Laforge Groovy Project Manager JSR-241 Spec Lead Initiator of the Grails framework Co-author of Groovy in Action By Dierk König, et al. Vice-President Technology
  • 4. Agenda What’s Grails? The Problem with the usual web frameworks The different layers Other cool features The plugin system Summary Q&A
  • 5. What’s Grails? From 10,000 feet From 1,000 feet Near the ground
  • 6. What’s Grails? (1/3) From 10,000 feet Grails is an MVC action-based framework Principles CoC : Convention over Configuration DRY : Don’t Repeat Yourself The essence of Ruby on Rails, but with the tight integration with the Java ecosystem Protect your investment!
  • 7. What’s Grails? (2/3) From 1,000 feet = + +
  • 8. What’s Grails? (3/3) Near the ground… Grails is built on proven & solid OSS bricks Spring : IoC, DI, Spring MVC, transactions… Hibernate : ORM, querying mechanism Groovy : for everything that matters SiteMesh : page layout and composition Quartz : for job scheduling AJAX : integration with different libraries Jetty & HSQLDB : for fast development cycles
  • 10. Why Groovy? Java-like syntax Flat learning curve The same programming models Same OO, security, threading models The same libraries JDK, and any in-house or OSS JAR And Groovy has… Closures, properties, malleable syntax for DSLs
  • 11. The Problem What’s the problem with Web frameworks? Why has it got to be complex? What are the pain points?
  • 12. Has it got to be complex? But it’s slow to start with Seting up the project takes time It gets complicated pretty rapidly Dive into Spring & Hibernate to wire everything together There are so many layers DAOs, DTOs, more abstraction layers Too many configuration files Often too much XML for everything Struts / Spring / Hibernate is okay…
  • 13. 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
  • 14. The Different Layers Bottom-up! Transparent persistence Controllers and services Groovy Server Pages, templates & taglibs
  • 15. Grails’ MVC at a Glance… Model GORM: Grails Object Relational Mapping Controller Multi-action controller Also the Service layer & Quartz job scheduling View GSP: Groovy Server Pages Tag libraries
  • 16. Pain Point #1 – Peristence ORM is quite hard to master and get right Many configuration files ibatis.xml hibernate.cfg.xml persistence.xml ejb-cmp.xml
  • 17. GORM – Grails Object Relational Mapping Hibernate under the hood Domain model is a set of POGOs Plain Old Groovy Objects POGOs are transparently mapped! No hibernate.cfg.xml But can be overriden if needed All domain classes get useful instance and static methods for free Book.count(), Book.list(), Book.get(id)… book.save(), book.delete(), book.update()…
  • 18. Example Grails provides a default ORM mapping strategy for Hibernate // A Book domain class class Book { String title Date releaseDate static belongsTo = [author: Author] } // A one-to-many class User { String name static hasMany = [bookmarks: Bookmark] } 18 8 Dec 2007 Groovy Recipes 17 2 11 Dec 2006 Groovy in Action 16 author_id release_date title id Dierk König 2 name id
  • 20. Constraints Constraints are added in domain classes through a static constraint field: static constraint = { isbn(matches: &quot;[0-9]{9}[0-9X]&quot;) } Many constraints available: blank, creditcard, email, blank, nullable, matches, range, unique, url… You can create your own validator myField(validator: { it % 2 == 0 })
  • 21. No more DAOs! Dynamic finder methods Book. findBy Title (&quot;The Stand&quot;) Book.findBy Title Like (&quot;Harry Pot%&quot;) Book.findBy ReleaseDate Between (start, end) Book.findBy Title LikeOr ReleaseDate LessThan ( &quot;%Grails%&quot;, someDate) Find by relationship Book.findAllByAuthor( Author.get(1) ) Affect sorting Book.findAllByAuthor( me, [sort: ‘title’, order: ‘asc’ ] )
  • 22. Querying Query by example Book.find ( new Book(title: ‘The Shining’) ) HQL queries Book.find( &quot; from Book b where b.title like ‘Lord of%’ &quot; ) Book.find( &quot; from Book b where b.title like ? &quot;, [ ‘Lord of%’ ] ) Criteria builder def results = Account.createCriteria() { like (&quot;holderFirstName&quot;, &quot;Fred%&quot;) and { between (&quot;balance&quot;, 500, 1000) eq (&quot;branch&quot;, &quot;London&quot;) } order (&quot;holderLastName&quot;, &quot;desc&quot;) }.list()
  • 23. Pain Point #2 – Services, Nav. & Pres. Logic Numerous layers Conf file chaos web.xml xwork.xml applicationContext.xml sitemesh.xml struts-config.xml validator.xml faces-config.xml tiles.xml
  • 24. Controllers class Book Controller { 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 = &quot;Book ${params.id} not found&quot; redirect(action:list) } else return [ book : book ] } } http://localhost:8080/myapp/ book / show
  • 25. Services & Scheduled Tasks 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 } Recuring events (Quartz) Intervals, or cron definitions class MyJob { def cronExpression = &quot;0 0 24 * * ?&quot; def execute() { print &quot;Job run!&quot; } }
  • 26. Pain Point #3 – The View Layer JSP cluttered with scriptlets Taglibs are painful c.tld fmt.tld spring.tld grails.tld struts.tld
  • 27. The view layer 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
  • 28. Groovy Server Pages <html> <head> <meta name=&quot;layout&quot; content=&quot;main&quot; /> <title>Book List</title> </head> <body> <a href=&quot; ${createLinkTo(dir:'')} &quot;>Home</a> <g:link action=&quot;create&quot;> New Book</g:link> <g:if test=&quot;${flash.message}&quot;> ${flash.message} </g:if> <g:each in=&quot; ${bookList} &quot;> ${it.title} </g:each> </body> </html>
  • 29. Dynamic Tag Libraries 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…
  • 30. Write your Own Taglib Yet another Grails convention class My TagLib { def isAdmin = { attrs , body -> def user = attrs['user'] if(user != null && checkUserPrivs(user)) body() } } Use it in your GSP <g:isAdmin user=&quot;${myUser}&quot;> some restricted content </g:isAdmin>
  • 31. What else? Custom URL mapping Conversation flows ORM DSL http://grails.org/GORM+-+ Mapping +DSL Develop with pleasure with IntelliJ IDEA http:// grails.org /IDEA+ Integration
  • 32. Custom URL Mappings (1/2) Pretty URLs in seconds Custom DSL for mapping URLs to controllers, actions and views Supports mapping URLs to actions via HTTP methods for REST Supports rich constraints mechanism
  • 33. Custom URL Mappings (2/2) Pretty URLs in seconds! class UrlMappings { static mappings = { &quot;/product/ $id &quot;(controller: &quot;product&quot;, action: &quot;show&quot;) &quot;/$blog/ $year? /$month?/$day?&quot;(controller: &quot;blog&quot;, action: &quot;show&quot;) { constraints { year(matches: /\d{4}/) } } }
  • 34. Conversations flows (1/2) Leverages Spring WebFlow Supports Spring’s scopes Request Session Conversation Flash Possibly to specify services’ scope DSL for constructing flows
  • 35. Conversations flows (2/2) Example: def searchFlow = { displaySearchForm { on(&quot;submit&quot;).to &quot;executeSearch&quot;   } executeSearch { action { [results: searchService. executeSearch(params.q)] } on(&quot;success&quot;).to &quot;displayResults&quot; on(&quot;error&quot;).to &quot;displaySearchForm&quot;  } displayResults() }
  • 36. Grails plugin system Beyond the out-of-the-box experience, extend Grails with plugins and write your own!
  • 37. Plugin Extension Points Extend Grails beyond what it offers! What can you do with plugins? Hook into the build system Script the Spring application context Register new dynamic methods Container configuration (web.xml) Adding new artefacts types Auto-reload your artefacts
  • 38. Plenty of Plugins! XFire Expose Grails services as SOAP Searchable Integrate Lucene & Compass search Remoting Expose Grails services over RMI, Burlap, or REST Google Web Toolkit Integrate Grails with GWT for the presentation layer Acegi / JSecurity Secure your Grails app JMS Expose services as message-driven beans
  • 39. Sweet spot: Enterprise-readiness Skills, libraries, app servers…
  • 40. Protect your Investment Reuse Existing Java libraries (JDK, 3rd party, in-house) Employee skills & knowledge (both prod & soft) 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 Java EE enterprise architecture!
  • 41. Let’s Wrap Up Summary Resources Q&A
  • 42. Summary Groovy is a powerful dynamic language for the JVM, that provides agile development on the Java platform, without the impedance mismatch of other languages  Groovy 1.1 out next week Grails is a fully-featured web application framework based on proven technologies like Spring and Hibernate , which simplifies the development of innovative applications  Grails 1.0 at the end of the month
  • 43. Resources Grails: http://grails.org Groovy: http://groovy.codehaus.org Groovy blogs: http://groovyblogs.org AboutGroovy: http://aboutgroovy.com Mailing-lists: http://grails.org/Mailing+lists G2One: http://www.g2one.com
  • 44. G2One, Inc. Groovy & Grails at the source! Graeme Rocher, Grails lead Guillaume Laforge, Groovy lead Plus key committers Professional Services Training, support, consulting Custom developments Connectors, plugins, etc…
  • 45. Q&A