Grails 0.3-SNAPSHOT Presentation WJAX 2006 English

Embed Size (px)

Citation preview

Grails

GRAILS


RAPID WEB APPLICATION DEVELOPMENT
MADE EASY

About: Sven Haiges

Actionality Deutschland GmbH

Senior Java Developer

Diplom-Informatiker (FH), MBA

My personal framework evolution:
Struts, JSF, Spring MVC, GRAILS

Since Juli 2006:
Grails Podcast, Grails Screencasts

Goals

What is Grails & how do I create my first Grails app?

What are the powerful cornerstones of Grails?

Which features does Grails provide out of the box?

Next Steps @ Home/Work

Agenda

Basics

Foundations

MVC

Features

Roadmap

Your Next Steps

Grails Basics

Grails MVC

Grails is an MVC Web Framework

Inspired by Ruby on Rails

Uses the powerful Groovy Scripting Language

Convention Over Configuration

Don't Repeat Yourself (DRY)

Grails History & Team

Started by Groovy enthusiasts: Guillaume LaForge, Steven Devijver and Graeme Rocher (current project lead)

0.1 was out March 29th, 2006

Current Team: Graeme Rocher, Marc Palmer, Dierk Koenig, Steven Devijer, Jason Rudolph, Sven Haiges... YOU!

Using Grails

Standalone

Configuration details are hidden

0..100 in no time!

Integrate with existing applications

Still use the flexibility of Grails for existing DB-Schemas, HBM-Mappings, Spring Configuration, etc.

Pimp your app!

Powerful Foundations

Foundations

Groovy: 1st class integration with Java Platform and all Java Code you have ever written!

Spring: IoC, Spring MVC, WebFlow, ...

Hibernate: powerful persistence Layer

SiteMesh: flexible layout framework

Installing Grails

No previous Groovy installation needed, just a Java VM 1.4+ (but does not hurt :-)

grails.org/Installation

Download, extract, set GRAILS_HOME, add bin to PATH, run it!

Type grails to verify it works

Your First Grails App

grails create-app

cd appName

grails run-app

grails create-domain-class, edit class

grails generate-all

grails run-app

Grails Foundations

Spring

Spring Framework is used to hold everything together

You can specify your own Spring Beans for injection into Controllers, Services, Jobs in spring/resources.xml

Good to know: a Grails app is an Spring MVC app... Spring Webflow to be used in future

Hibernate

Hibernate is the de facto standard for O/R Mapping

Grails maps your Domain Classes automatically, even creates and exports the schema to the database

1:n & m:n supported!

Great flexibility: use your own HBM files for legacy database schemas!

SiteMesh

SiteMesh is a powerful Layout Framework and integrated into Grails

grails-app/views/layout/main.gsp is the standard layout file

This meta element in a head of a gsp file links it with the main layout:

Grails Philosophy

Reuse (see foundations)

No reinventing the wheel

Coding by Convention

without being locked into a single solution!

Domain-Centric, not DB-Centric

DRY

Grails MVC

Model

Above is a Domain Class

.groovy files living in grails-app/domain

Persistent

id, version, equals, hashCode, toString is generated automatically, but can be overridden

class Book {

String title

}

Model

You will typically use this convenience target to create Domain Classes

Will ask you for the name, make it uppercase if you forget

> grails create-domain-class

Model

1:1 mapping with Author

Specify the owning side with this

class Book {

Author author

String title

}

class Book {

def belongsTo = Author

Author author

String title

}

Model

1:n mapping: Author has many Books

Property books created automatically

Same for adder method:

class Author {

def hasMany = [ books : Book ]

String name

}

author.addBook(new Book(title:'Grails'))

author.save()

Model

m:n possible, too!

BelongsTo defines owning side

class Book {

def belongsTo = Author

def hasMany = [authors:Author]

}

class Author {

def hasMany = [books:Book]

}

Model

Constraints defined via constraints closure

Affects generation of views, too!

class User {

String login

String password

String email

Date age

static constraints = {

login(length:5..15,blank:false,unique:true)

password(length:5..15,blank:false)

email(email:true,blank:false)

age(min:new Date(),nullable:false)

}

}

Model

Dynamic Finder Methods

def results = Book.findByTitle("The Stand")

results = Book.findByTitleLike("Harry Pot%")

results = Book.findByReleaseDateBetween( firstDate, secondDate )

results = Book.findByReleaseDateGreaterThan( someDate )

You can also use Query by Example (QBE) the Hibernate Criteria Builder, or direct HQL queries!

Model

Database configuration is done in
grails-app/conf directory

DevelopmentDataSource.groovy

ProductionDataSource.groovy

TestDataSource.groovy

If you hit grails run-app the dev datasource is the default

Model

grails war creates your deployment war file with the production datasource

class DevelopmentDataSource {

boolean pooling = true

// one of 'create', 'create-drop','update'

//String dbCreate = "create-drop"

String url = "jdbc:postgresql://localhost:5432/act_dev"

String driverClassName = "org.postgresql.Driver"

String username = "dev"

String password = "devpw"

def logSql = true //enable logging of SQL generated by Hibernate

}

Model

BootStrap files are picked up at startup and can be used to create initial (test) data

class CompanyBootStrap {

def init = { servletContext ->

//Delete all data in the tables that we work on

Company.executeUpdate("delete Company")

//now create the test data

Company c1 = new Company(name:'bmw')

c1.addUser(new User(name:'herbert', admin:true, ...))

.save()

}

...

View

Groovy Server Pages(GSP) or
JavaServer Pages (JSP)

TagLibs for both, but GSP is groovin'

All views are in the grails-app/views directory

Generate views for your domain class:
grails generate-views

View

Example GSP / uses main Layout

BlogEntry List


Home

New BlogEntry

...

...

View

Dynamic Tag Libraries

Tags are fun again!

grails create-taglib

A plain *TagLib.groovy file in grails-app/taglib

As with GSPs & Controllers: no server restart!

View

TagLib example (simple tag)

class MyTagLib {

includeJs = { attrs ->

out

mkp {

div('class':'dialog') {

body()

}

}

}

Above example uses a Groovy MarkupBuilder

Controller

All controllers are mapped to the Grails dispatcher servlet

Create a new controller via:
grails create-controller

Or generate the controller based on an existing Domain Class:
grails generate-controller

Controller

Default Mapping Convention
http://.../appName/controller/action/id

Some properties automatically available

flash map stores messages for next request

log - a Log4J logger instance

params map with all request parameters

request/response/servletContext etc.

Controller

Example generated controller:

class AdvertisementController {

def index = { redirect(action:list,params:params) }

def list = {

[ advertisementList: Advertisement.list( params ) ]

}

def show = {

[ advertisement : Advertisement.get( params.id ) ]

}

...

Controller

You can also use dynamic scaffolding:

class BookController {

def scaffold = Book

}

list/show/edit/delete/create/save/
update dynamically available

You can still override actions

grails generate-all creates all views and all controller actions for a domain class

Controller

Grails Services can be used to encapsulate business logic

Services may be injected into Controllers

grails create-service creates a new service in grails-app/services

Controller

Example Service

class CountryService {

def String sayHello(String name) {

return "hello ${name}"

}

}

Used within a controller

class GreetingController {

CountryService countryService

def helloAction = {

render(countryService.sayHello(params.name))

}

}

About Scaffolding...

Use it to get up to speed, have something to show and work on

You will not scaffold your complete web application

Learn from the generated code, tweak it to fit your individual needs

Grails Features

Auto Reloading

In development mode, Grails synchronizes the current application with the server

Controllers, GSPs, Tag Libraries, Domain Classes, Services, etc.

This is essential for an iterative and incremental development.

Call it agile if you like!

Spring Integration

You can put additional Spring configuration in the /spring directory and use it to configure your beans

Automatic DI is available even for these beans (not just Services)

Easily integrate existing (Java) functionality that was configured with Spring

Hibernate Integration

You can specify your own HBM files for your domain classes. (You can even use your existing Java classes if you like)

Working with legacy database schemas is getting really simple

Still use all benefits like dynamic finder methods

Eclipse Integration

Grails creates an Eclipse Project file automatically, just run
File > Import > Existing Project

You'll have to tweak some file names if you use the development snapshot versions

Be sure to install the Groovy Plugin:
groovy.codehaus.org/Eclipse+Plugin

AJAX

Grails supports AJAX with different AJAX toolkits, currently Prototype, Dojo and Yahoo

Special AJAX tags can be used for asynchronous calls and form submission

Delete Book

AJAX

On the server side, Grails supports AJAX via the render() Method, which makes AJAX responses really easy:

def time = {

render(contentType:'text/xml') {

time(new Date())

}

}

Render() supports MarkupBuilders for XML, HTML, JSON, OpenRico

Job Scheduling

Grails makes using Quartz even easier, just create this (in grails-app/jobs):

class MyJob {

def cronExpression = "0,15,30,45 * * * * ?" //every 15 seconds

def execute(){

println "Running job!"

}

}

Unit & Functional Testing

Both unit and functional testing supported

Functional Testing uses Canoo Webtest

grails test-app runs the unit tests

grails run-webtest

Generate a webtest with

grails generate-webtest

Grails Roadmap

The Sandbox

New Controllers

Page Flows

Constraints for DB-Schema creation

Laszlo on Grails

Mail / Messaging Integration

Test DataSets

Plugin-System

Roadmap

0.3

Spring 2

Web Services Service Classes

M:N Mapping for GORM

0.4

DWR Support for Service Classes

Pluggable Persistence Layer

Roadmap

0.5

XML-RPC for Service Classes

Generation of Domain Model from DB Schema

0.6

Scaffolding of User Authentication Code

Grails is user-centric, you define what really happens. Vote in Jira: http://jira.codehaus.org/browse/GRAILS

Your Next Steps

Learn more

Download, Install, create your first app with the Quickstart Guide
http://www.grails.org/Quick+Start

Check out the Tutorials Section
http://www.grails.org/Tutorials

Learn more

Read & Work through the user guide
http://www.grails.org/User+Guide

Get onto the Grails user mailing list
http://www.grails.org/Mailing+lists

Remember: Grails is open source...

The more you contribute, the more you get out in terms of learning, jobs, contacts...

Watch

Currently two screencasts available

Scaffolding

Directory Structure

http://www.grails.org/Grails+Screencasts

Listen

Grails Podcast

Weekly Show

Grails News

Grails Features

Interviews

Agile Development

http://hansamann.podspot.de/rss

Read

Out soon!

By Graeme Rocher,
Grails Project Lead

ISBN: 1-59059-758-3

Contribute

Be part of the community

Contribute a Tag!
grails.org/Contribute+a+Tag

Blog about Grails! Now!

Answer questions on the Grails Users List!

and...

Groovy & Grails Shop

Buy your girlfriend one of those sexy Groovy GStrings

http://tinyurl.com/y3zmos

New!

GRAILS

RAPID WEB APP DEVELOPMENT
MADE EASY

Questions?

www.grails.org
www.svenhaiges.de

Click to edit the title text format

Click to edit the outline text format

Second Outline Level

Third Outline Level

Fourth Outline Level

Fifth Outline Level

Sixth Outline Level

Seventh Outline Level

Eighth Outline Level

Ninth Outline Level