Você está na página 1de 13

Goals

GRAILS
• 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?

RAPID WEB APPLICATION DEVELOPMENT


MADE EASY
originally written by Sven Haiges
and adapted by Jürg Luthiger

(C) Hochschule für Technik

15/01/2008 1 15/01/2008 Fachhochschule Nordwestschweiz


2

Agenda
Grails MVC
• Grails Basics • Grails is an MVC Web Framework
• Grails Foundation – Inspired by Ruby on Rails
• Grails MVC – Uses the powerful Groovy Scripting Language
– Convention Over Configuration
• Grails Features
– Don't Repeat Yourself (DRY)

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
3 15/01/2008 Fachhochschule Nordwestschweiz
4
Grails History & Team Using Grails
• Standalone
• Started by Groovy enthusiasts: Guillaume LaForge, Steven Devijver
and Graeme Rocher (current project lead) – Configuration details are hidden
• 0.1 was out March 29th, 2006 – 0..100 in no time!
• Current version 1.0 RC3 • Integrate with existing applications
• Current Team: Graeme Rocher, Marc Palmer, Dierk Koenig, Steven – Still use the flexibility of Grails for existing DB-Schemas, HBM-Mappings,
Devijer, Jason Rudolph, Sven Haiges... Spring Configuration, etc.
– Pimp your app!

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
5 15/01/2008 Fachhochschule Nordwestschweiz
6

Powerful Foundations Installing Grails


• Foundations • No previous Groovy installation needed
– Groovy: 1st class integration with Java Platform and all Java Code you – just a Java VM 1.4 or higher
have ever written! – See grails.codehaus.org/Installation
– Spring: IoC, Spring MVC, WebFlow, ... • Download and extract
– Hibernate: powerful persistence Layer – set GRAILS_HOME
– SiteMesh: flexible layout framework – add bin to PATH
• Type grails to verify it works

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
7 15/01/2008 Fachhochschule Nordwestschweiz
8
Agenda
Your First Grails App
• Grails Basics
$grails create-app
• Grails Foundation
show directory structure
$cd helloworld • Grails MVC
$grails help • Grails Features
integrate Grails app into eclipse
$grails create-controller
$grails run-app
show dynamic update, edit controller class
add spring bean

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
9 15/01/2008 Fachhochschule Nordwestschweiz
10

Spring Hibernate

• Spring Framework is used to hold everything together • Hibernate is the de facto standard for O/R Mapping
• You can specify your own Spring Beans for injection into Controllers, • Grails maps your Domain Classes automatically, even creates and
Services, Jobs in spring/resources.xml exports the schema to the database
• Good to know: a Grails app is an Spring MVC app... Spring Webflow to – 1:n & m:n supported!
be used in future • Great flexibility: use your own HBM files for legacy database schemas!

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
11 15/01/2008 Fachhochschule Nordwestschweiz
12
SiteMesh Grails Philosophy

• SiteMesh is a powerful Layout Framework and integrated into Grails • Reuse (see foundations)
• grails-app/views/layout/main.gsp is the standard layout file • No “reinventing the wheel”
• This meta element in a head of a gsp file links it with the “main” layout: • Coding by Convention
<meta name="layout" content="main" /> – without being locked into a single solution!
• Domain-Centric, not DB-Centric
• DRY

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
13 15/01/2008 Fachhochschule Nordwestschweiz
14

Agenda Model

• Grails Basics class Book {


• Grails Foundation String title
}
• Grails MVC
• Grails Features • 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

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
15 15/01/2008 Fachhochschule Nordwestschweiz
16
Model Model

class Book {
> grails create-domain-class Author author
String title
}

• You will typically use this convenience target to create Domain • 1:1 mapping with Author
Classes • Specify the “owning side” with this
• Will ask you for the name, make it uppercase if you forget
class Book {
def belongsTo = Author
Author author
String title
}

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
17 15/01/2008 Fachhochschule Nordwestschweiz
18

Model Model

class Author {
• m:n possible, too!
def hasMany = [ books : Book ]
String name • BelongsTo defines “owning side”
}

• 1:n mapping: Author has many Books class Book {


• Property “books” created automatically def belongsTo = Author
def hasMany = [authors:Author]
• Same for adder method:
}

class Author {
author.addBook(new Book(title:'Grails'))
def hasMany = [books:Book]
author.save()
}

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
19 15/01/2008 Fachhochschule Nordwestschweiz
20
Model Model

• Constraints defined via constraints closure


• Affects generation of views, too! • Dynamic Finder Methods

class User { def results = Book.findByTitle("The Stand")


String login results = Book.findByTitleLike("Harry Pot%")
String password results = Book.findByReleaseDateBetween( firstDate, secondDate )
String email
results = Book.findByReleaseDateGreaterThan( someDate )
Date age
static constraints = {
login(length:5..15,blank:false,unique:true)
password(length:5..15,blank:false)
• You can also use Query by Example (QBE)
email(email:true,blank:false) the Hibernate Criteria Builder, or direct
}
age(min:new Date(),nullable:false)
HQL queries!
}

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
21 15/01/2008 Fachhochschule Nordwestschweiz
22

Model Model

class DevelopmentDataSource {
• Database configuration is done in boolean pooling = true
grails-app/conf directory // one of 'create', 'create-drop','update'
– DevelopmentDataSource.groovy //String dbCreate = "create-drop"

– ProductionDataSource.groovy String url = "jdbc:postgresql://localhost:5432/act_dev"


String driverClassName = "org.postgresql.Driver"
– TestDataSource.groovy
String username = "dev"
• If you hit “grails run-app” the dev datasource is the default
String password = "devpw"
def logSql = true //enable logging of SQL generated by
Hibernate
}

• “grails war” creates your deployment war file with the production datasource

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
23 15/01/2008 Fachhochschule Nordwestschweiz
24
Model View

• BootStrap files are picked up at startup and can be used to create • Groovy Server Pages(GSP) or
initial (test) data 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:
class CompanyBootStrap {
“grails generate-views”
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()
}
...

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
25 15/01/2008 Fachhochschule Nordwestschweiz
26

View View

• Example GSP / uses “main” Layout • Dynamic Tag Libraries


• Tags are fun again!
<html>
<head> • “grails create-taglib”
<meta name="layout" content="main" />
<title>BlogEntry List</title>
• A plain *TagLib.groovy file in grails-app/taglib
</head> • As with GSPs & Controllers: no server restart!
<body>
<div class="nav">
<span class="menuButton">
<g:link controller="authentication" action="viewControllers" >Home</g:link></span>
<span class="menuButton"><g:link action="create">New BlogEntry</g:link></span>
</div>
<div class="body">
...
</div>
...

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
27 15/01/2008 Fachhochschule Nordwestschweiz
28
View View

• TagLib example (“simple” tag) • Logical and iterative tags just as easy.
• You can even call tags as “methods” within GSP – here used as
class MyTagLib { normal tag:
includeJs = { attrs ->
out << "<script src='scripts/${attrs['script']}.js' />"
}
<g:hasErrors bean="${book}" field="title">
}
<span class='label error'>There were errors on the book title</span>
</g:hasErrors>

• OutputStream is available via “out”


• All attributes are in the attrs map • Or as method:
• Usage of GStrings keeps tags readable <span id="title" class="label ${hasErrors(bean:book,field:'title','errors')}">Title</span>

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
29 15/01/2008 Fachhochschule Nordwestschweiz
30

View Controller

• Creating markup from tags is a piece of cake: • All controllers are mapped to the Grails dispatcher servlet
• Create a new controller via:
“grails create-controller”
def dialog = { attrs, body -> • Or generate the controller based on an existing Domain Class:
mkp { “grails generate-controller”
div('class':'dialog') {
body()
}
}
}

• Above example uses a Groovy


MarkupBuilder

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
31 15/01/2008 Fachhochschule Nordwestschweiz
32
Controller Controller

• Example generated controller:


• Default Mapping Convention
http://.../appName/controller/action/id class AdvertisementController {
• Some properties automatically available def index = { redirect(action:list,params:params) }
– flash – map stores messages for next request
– log - a Log4J logger instance def list = {
– params – map with all request parameters [ advertisementList: Advertisement.list( params ) ]
– request/response/servletContext etc. }

def show = {
[ advertisement : Advertisement.get( params.id ) ]
}
...

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
33 15/01/2008 Fachhochschule Nordwestschweiz
34

Controller Controller

• You can also use dynamic scaffolding: • Grails Services can be used to encapsulate business logic
• Services may be injected into Controllers
class BookController {
def scaffold = Book
• “grails create-service” creates a new service in grails-app/services
}

• 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
(C) Hochschule für Technik (C) Hochschule für Technik
15/01/2008 Fachhochschule Nordwestschweiz
35 15/01/2008 Fachhochschule Nordwestschweiz
36
Controller About Scaffolding...

• Example Service • Use it to get up to speed, have something to show and work on
• You will not scaffold your complete web application
class CountryService {
def String sayHello(String name) { • Learn from the generated code, tweak it to fit your individual needs
return "hello ${name}"
}
}

• Used within a controller


class GreetingController {
CountryService countryService
def helloAction = {
render(countryService.sayHello(params.name))
}
}

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
37 15/01/2008 Fachhochschule Nordwestschweiz
38

Agenda Auto Reloading

• Grails Basics • In development mode, Grails synchronizes the current application


• Grails Foundation with the server
• Grails MVC • Controllers, GSPs, Tag Libraries, Domain Classes, Services, etc.
• Grails Features • This is essential for an iterative and incremental development.
• Call it “agile” if you like!

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
39 15/01/2008 Fachhochschule Nordwestschweiz
40
Spring Integration Hibernate Integration

• You can put additional Spring configuration in the /spring directory • You can specify your own HBM files for your domain classes. (You
and use it to configure your beans can even use your existing Java classes if you like)
• Automatic DI is available even for these beans (not just Services) • Working with legacy database schemas is getting really simple
• Easily integrate existing (Java) functionality that was configured • Still use all benefits like dynamic finder methods
with Spring

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
41 15/01/2008 Fachhochschule Nordwestschweiz
42

Eclipse “Integration” AJAX

• Grails creates an Eclipse Project file automatically, just run • Grails supports AJAX with different AJAX toolkits, currently
File > Import > Existing Project Prototype, Dojo and Yahoo
• You'll have to tweak some file names if you use the development • Special AJAX tags can be used for asynchronous calls and form
snapshot versions submission
• Be sure to install the Groovy Plugin:
groovy.codehaus.org/Eclipse+Plugin

<div id="message"></div>
<g:remoteLink action="delete" id="1" update="message">Delete
Book</g:remoteLink>

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
43 15/01/2008 Fachhochschule Nordwestschweiz
44
AJAX Job Scheduling

• On the server side, Grails supports AJAX via the render() Method, • Grails makes using Quartz even easier, just create this (in grails-
which makes AJAX responses really easy: app/jobs):

class MyJob {
def time = {
def cronExpression = "0,15,30,45 * * * * ?" //every 15 seconds
render(contentType:'text/xml') {
def execute(){
time(new Date())
println "Running job!"
}
}
}
}
• Render() supports MarkupBuilders for XML,
HTML, JSON, OpenRico
(C) Hochschule für Technik (C) Hochschule für Technik
15/01/2008 Fachhochschule Nordwestschweiz
45 15/01/2008 Fachhochschule Nordwestschweiz
46

Unit & Functional Testing Learn more

• Both unit and functional testing supported • Download, Install, create your first app with the Quickstart Guide
• Functional Testing uses Canoo Webtest http://www.grails.org/Quick+Start
– “grails test-app” runs the unit tests • Check out the Tutorials Section
– “grails run-webtest” http://www.grails.org/Tutorials
• Generate a webtest with
– “grails generate-webtest”

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
47 15/01/2008 Fachhochschule Nordwestschweiz
48
Learn more Read

• Read & Work through the user guide • By Graeme Rocher,


http://www.grails.org/User+Guide Grails Project Lead
• Get onto the Grails user mailing list • ISBN: 1-59059-758-3
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...

(C) Hochschule für Technik (C) Hochschule für Technik


15/01/2008 Fachhochschule Nordwestschweiz
49 15/01/2008 Fachhochschule Nordwestschweiz
50

Você também pode gostar