grails introduction - ijtc 2007
DESCRIPTION
Introduction to the Grails web framework at the Irish Java Technology Conference 2007TRANSCRIPT
GrailsWeb app development with pleasure!
Guillaume LaforgeVice-President, TechnologyG2One, Inc.http://www.g2one.com
IJTC 2007 | Grails www.dubjug.org
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!
IJTC 2007 | Grails www.dubjug.org
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
IJTC 2007 | Grails www.dubjug.org
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 feetFrom 1,000 feetNear the ground
IJTC 2007 | Grails www.dubjug.org
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!
IJTC 2007 | Grails www.dubjug.org
What’s Grails? (2/3) From 1,000 feet
=+ +
IJTC 2007 | Grails www.dubjug.org
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
IJTC 2007 | Grails www.dubjug.org
The Grails Stack
IJTC 2007 | Grails www.dubjug.org
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?
IJTC 2007 | Grails www.dubjug.org
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…
IJTC 2007 | Grails www.dubjug.org
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
IJTC 2007 | Grails www.dubjug.org
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
IJTC 2007 | Grails www.dubjug.org
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
IJTC 2007 | Grails www.dubjug.org
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()…
IJTC 2007 | Grails www.dubjug.org
Example Grails provides a default ORM mapping
strategy for Hibernate
// A Book domain classclass Book { String title Date releaseDate static belongsTo = [author: Author]}
// A one-to-manyclass User { String name static hasMany = [bookmarks: Bookmark]}
id title release_date author_id
16 Groovy in Action
11 Dec 2006 2
17 Groovy Recipes 8 Dec 2007 18
id name
2 Dierk König
<DEMO/>
IJTC 2007 | Grails www.dubjug.org
Constraints Constraints are added in domain classes
through a static constraint field: static constraint = { isbn(matches: "[0-9]{9}[0-9X]") }
Many constraints available: blank, creditcard, email, blank, nullable,
matches, range, unique, url… You can create your own validator
myField(validator: { it % 2 == 0 })
IJTC 2007 | Grails www.dubjug.org
No more DAOs! 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’] )
IJTC 2007 | Grails www.dubjug.org
Querying 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()
IJTC 2007 | Grails www.dubjug.org
Pain Point #2 – Services, Nav. & Pres. Logic
Numerous layers Conf file chaos
web.xmlxwork.xml
applicationContext.xml
sitemesh.xml
struts-config.xml
validator.xml
faces-config.xml
tiles.xml
IJTC 2007 | Grails www.dubjug.org
Controllers class 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 ] } } http://localhost:8080/myapp/book/show
IJTC 2007 | Grails www.dubjug.org
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 = "0 0 24 * * ?" def execute() { print "Job run!" }}
IJTC 2007 | Grails www.dubjug.org
Pain Point #3 – The View Layer JSP cluttered with scriptlets Taglibs are painful
c.tld
fmt.tld
spring.tld
grails.tld
struts.tld
IJTC 2007 | Grails www.dubjug.org
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
IJTC 2007 | Grails www.dubjug.org
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>
IJTC 2007 | Grails www.dubjug.org
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…
IJTC 2007 | Grails www.dubjug.org
Write your Own Taglib 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>
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
IJTC 2007 | Grails www.dubjug.org
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
IJTC 2007 | Grails www.dubjug.org
Custom URL Mappings (2/2) Pretty URLs in seconds!
class UrlMappings {
static mappings = {
"/product/$id"(controller: "product", action: "show")
"/$blog/$year?/$month?/$day?"(controller: "blog",
action: "show") { constraints { year(matches: /\d{4}/) } }}
IJTC 2007 | Grails www.dubjug.org
Conversations flows (1/2) Leverages Spring WebFlow Supports Spring’s scopes
Request Session Conversation Flash
Possibly to specify services’ scope DSL for constructing flows
IJTC 2007 | Grails www.dubjug.org
Conversations flows (2/2) Example: def searchFlow = { displaySearchForm { on("submit").to "executeSearch" } executeSearch { action { [results: searchService. executeSearch(params.q)] } on("success").to "displayResults" on("error").to "displaySearchForm" } displayResults()}
Grails plugin systemBeyond the out-of-the-box experience,extend Grails with pluginsand write your own!
IJTC 2007 | Grails www.dubjug.org
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
IJTC 2007 | Grails www.dubjug.org
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…
IJTC 2007 | Grails www.dubjug.org
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
IJTC 2007 | Grails www.dubjug.org
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
IJTC 2007 | Grails www.dubjug.org
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
IJTC 2007 | Grails www.dubjug.org
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