Introduction To Grails

91
INTRODUZIONE A GRAILS a cura di Paolo Foletto

Transcript of Introduction To Grails

Page 1: Introduction To Grails

INTRODUZIONE A GRAILSa cura di Paolo Foletto

Page 2: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 2

An Introduction to Grails

Learning by example developing a web application JugEvents using Netbeans

Page 3: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 3

Why this presentation?

[email protected]

Page 4: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 4

Index of presentation

1)Motivations for Grails 2)Instructions for installation3)MVC4)Groovy5)Dinamic scaffold6)GORM Object Relational Mapping7)Controller and views

Page 5: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 5

What's is specific in this in this introduction?Very easy e simple,Quick startbeginners with no Java knowledge :)Creating a very simple web application with persistent data without learning using a database?

Page 6: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 6

Can you ...

Using a persistence system without knowing that it exists?You can!

Page 7: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 7

What is Grails?

Grails is an open source web framework powered by the Groovy – language based on Java Virtual Machine.Groovy is a language compiled

Hiding a lot of information

Hiding a lot of unnecessary configuration details it brings a clear web-development enviroment. Grails runs on a standard servlet container, which enables you to choose your own presentation technology, no matter if it’s JSP or GSP based.

Page 8: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 8

Why you should consider Grails?

1)Extremely simplified and speedy development2)Ready to run3)Great templating, Custom Tags

Java compatibility :) Spring based ;)

Page 9: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 9

SpringSource - Weapons for the War on Java Complexity http://blog.springsource.com/2008/11/11/more-weapons-for-the-war-on-complexity-springsource-acquires-groovygrails-leader/

Page 10: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 10

Graeme Rocher

As Head of Grails Development for SpringSource, Graeme Rocher is the project lead and co-founder of the Grails web application framework. He's a member of the JSR-241 Expert Group which standardizes the Groovy language. Graeme authored the Definitive Guide to Grails for Apress and is a frequent speaker at JavaOne, JavaPolis, NoFluffJustStuff, JAOO, the Sun TechDays and more. Graeme joined SpringSource in late 2008 upon the acquisition of G2One Inc.

Page 11: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 11

Because it’s easy to start with

Grails offers an easy start for experienced Java developers as well as beginners with no Java knowledge. All thanks to Groovy. If you write some Java code it’s very likely that with groovy the same code will be MUCH shorter, yet giving the same result. On the other hand – do you have some custom, nice Java libraries and you want to use them again? No problem. Just import them like you always do in Java files. Cool, isn’t it?

Page 12: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 12

Ready to run

With Grails (1.x) you get an server and a db ready to run.Jetty server and HSQLDB as database.

With the next release of Grails (1.2) the server is Tomcat At the moment the version 1.2 is M3

Page 13: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 13

Great templating, Custom Tags

You can define your templates and use them in your Grails application with ease.Creating custom tag in Grails is a breeze, thanks to the rich plug ins database it’s very easy to add any AJAX or JavaScript based solution.

Page 14: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 14

Why the name Grails ?

Inspired by Ruby On Rails

Convention Over ConfigurationDRY Don't Repeat YourselfExploits the power of GroovyThree environment development, test and productionFull stack of MVC ( Model View Controller) Framework for Web Application

Page 15: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 15

What you need to know to start?

The information you need to know is: there is a good architecture in which everything go easily to the right placeMuch of Grails’s ability to support rapid application development comes from its emphasis on convention over configuration. The Grails project structure relies heavily on convention and establishes a sensible organizational structure for an application’s various artifacts.

Page 16: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 16

Groovy

Groovy is an agile and dynamic language for the

Java Virtual Machinemakes modern programming features available to Java developers with almost-zero learning curveseamlessly integrates with all existing Java objects and librariesIncreases developer productivity by reducing scaffolding code when developing web, GUI, database or console applications

Page 17: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 17

Groovy Syntax Compared to Java

● The first thing you’ll notice in a block of Groovy code is the lack of semicolons; in Groovy, semicolons are optional. Return statements are also optional.

● If there is no return statement in a method, then the last statement evaluated is returned.

Page 18: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 18

Groovy Syntax Compared to Java

● Methods without arguments need the parentheses so that Groovy can tell them apart from properties. Groovy provides “real” properties.

● All fields in a Groovy class are given getters and setters at compile time.

Page 19: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 19

Groovy Strings

● Groovy adds a new string known as a GString. A GString can be created by declaring a literal with double quotes; a string literal with single quotes is a java.lang.String. A GString can be used in place of a Java String. If a method is expecting a String and is given a GString, it will be cast at runtime.

● The beauty and power of the GString is its ability to evaluate embedded Groovy expressions. Groovy expressions can be designated in two ways.

Page 20: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 20

def firstName = “Paolo”def lastName = “Foletto”def groovyString = ''$firstName , $lastName”assert groovyString == 'Paolo , Foletto'def groovyString = ''${firstName} , ${lastName}”

Page 21: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 21

Groovy Closures

A Groovy closure, in simple terms, is an executable block of code that can be assigned to a variable, passed to a method, and executed.Also the variables that are in the scope of the definition of the closure are available to the closureClosure can take parameters explicit and implicitdef c = {a, b -> a + b}it is the name of implicit parameter

Page 22: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 22

def name = 'Lucio'def c = {println "$name called this closure ${it+1} time${it > 0 ? 's' : ' ' }"}assert c instanceof Closure4.times(c)

Lucio called this closure 1 timeLucio called this closure 2 timesLucio called this closure 3 timesLucio called this closure 4 times

Page 23: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 23

1.The variable name is available when the closure is executed.

Anything that is in scope when the closure is created will be available when it is executed, even if it is being executed by code in a different class. The closure is being assigned to the variable c and has no declared parameters. It does have and use the implicit parameter it.

Page 24: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 24

● What would be in Java System.out.println( ) is now just println( ).

● The method times passes an integer as implicit parameter

Page 25: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 25

Getting Started

And now we start with the installation, assuming that Java is already installed ... Download and unzip grails.zip from the GrailsAbout 33 Mb for the version 1.1.1 site: www.Grails.orgSet GRAILS_HOME environment variablesAdd to $GRAILS_HOME/bin to the path

Page 26: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 26

Grails and NetBeans

Excellent support for Grails in NetBeansCreating projectRunning projectRunning browserCommand grailsInstalling plugin

Page 27: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 27

Download ad install NetBeans

After install Grails, download and install the lastest version of NetBeans, at the moment the released version is 6.7.1If you have a JDK installed you can dowload a bundle.

Page 28: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 28

Getting Started

Create an application “MyFirstProject”Run “grails create-app MyFirstProject”

Run “grails create-domain-class People”Edit people.grovyRun “grails generate-all”Run “grails run-http”

Page 29: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 29

MVC (Model View Controller)

A design pattern used in services architectures. Contains 3 distinct elements :

The 'Model' is how the underlying data is structured.

The 'View' is what is presented to the user or consumer.

The 'Controller' is the element that performs the processing.

Page 30: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 30

Domain Classes

The “Model”Stick to the rules :Let the controller do the controllingLet the view do the viewingMay define validation constraints

Page 31: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 31

Grails treats the domain classes as the central and most important component of the application. It’s from the domain classes that we’ll drive everything else that we do in the application. (If you’ve worked with Ruby on Rails, you’ll notice that this is a departure from the Rails approach, where Rails derives the domain model from the underlying database schema.)

Page 32: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 32

Views

The ViewsGroovy Server Pages (GSP)

– By convention the action use a view with the same name

– For example the action show go to view show– In other frameworks you configure using XML the

relation between action and viewCustom tag libraries

Page 33: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 33

One FAQ from Grails Site

View TechnologiesQ: When I point my browser at a particular page of my application, I get a 404 error that says <something>.jsp could not be found. I am using GSPs, so why is Grails looking for a JSP file that doesn't exist?When you get this error, Grails has already looked for the appropriate GSP file but not found it. It then looks for a suitable JSP file and if that can not be found, you get the error about the JSP file. So if you are using GSPs and see this error, you need to check that the GSP file is in the right place with the correct name.

Page 34: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 34

Convention on the name of the URL

http://localhost:8080/jugevents/event/ http://localhost:8080/jugevents/event/create http://localhost:8080/jugevents/jug/show/1

Application contextControllerAction ( optional) (default = 'index')Record ID (optional)

Page 35: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 35

Grails then looks for a component specifying the action to invoke within the given controller. If the URL includes the action, then Grails will invoke that action in the controller. (Again, if the action does not exist, we’ll get an error.) If the URL does not include an action, Grails invokes the default action for the controller. Unless otherwise specified in the controller, Grails looks for an action named “index” as the default action

Page 36: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 36

Scaffolding

Dynamic and generated codeThe generated code easy to learn

Page 37: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 37

● An example application: JugEvents :)

Page 38: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 38

● We start creating a new project, we choose a Grails application, the first time we had to configure where is installed Grails

Page 39: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 39

● We can observe the structure of the directories that was created by the command

● The command is a script groovy

● We are interested in– Domain classes– Controllers– Views and Layouts

Page 40: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 40

We check the content of the directoryThere is something in ● Configuration● Message Bundles● Web application

Page 41: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 41

Grails treats the domain classes as the central and most important component of the application. It’s from the domain classes that we’ll drive everything else that we do in the application. (If you’ve worked with Ruby on Rails, you’ll notice that this is a departure from the Rails approach, where Rails derives the domain model from the underlying database schema.)

Page 42: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 42

Domain Class Event

$ grails create-domain-class EventAnd then we add some properties

String title

Date startDate

Date endDate

String location

String directions

String description

String organizer

Date creationDate

Page 43: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 43

Before we move on to the controllers, notice for a moment that there’s nothing in these classes that mentions any kind of Object Relational Mapping (ORM) or persistence. These classes don’t seem to extend any other classes that provide that functionality.They don’t implement any interface that might identify these classes as needing persistence. Neither do they include any associations to classes that might provide persistence services.And, we didn’t edit any configuration files. What tells Grails that these classes need persistence support?Convention removes the need for any of these approaches.

Page 44: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 44

Domain Class Event

Page 45: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 45

Convention on the name of the controller

Page 46: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 46

● Create a controller● Create a single method scaffold of one line● And start the application● NetBeans gentle starts the browser● Select the event controller● Create a new event● Observe the result and the convention

Page 47: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 47

http://localhost:8080/jugevents/event/ http://localhost:8080/jugevents/event/create http://localhost:8080/jugevents/jug/show/1

Convention on the name of the controller, action, id

Page 48: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 48

What we can see? And what not? Where is title?Sortable columnsLink to the new item

Page 49: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 49

● Creating an event, title there is

Page 50: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 50

● We can add some constraints to modify the order of the fields , we edit the Event class

Page 51: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 51

Change the order of the fields

● By default Grails shows the first six fields in alfabetical order but we can change very easily

Page 52: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 52

Dimension

description(maxSize:5000)

Page 53: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 53

The constraints consist of a code block, which is a Groovy closure.Inside this block, we list each of our properties, followed by parentheses. Inside the parentheses, we can include one or more key/value pairs that represent rules for that property. The order of the properties in the constraints block will be used to determine the display order in the scaffolded views. The maxSize constraint that we added to the description property will affect how that property is displayed in the views and will also affect the database schema generation. For example, in MySQL, the description field will be of type TEXT, whereas nonconstrained String properties will render fields of VARCHAR(255).

Page 54: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 54

Bootstrap

● The BootStrap.groovy has a method init that is executed at the bootstrap of the application

● We can initialize some dataWe are using the database with the configuration create/drop because for the first stages of development of the application it is very fast to create and drop the db at every restart.

Page 55: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 55

● Now we can add another Domain Class Jug

Page 56: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 56

● Create a controller with the method scaffold● Add a Jug in BootStrap● Restart the application● We have two controllers

Page 57: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 57

Model a relation One to One

● We want model a relation One to One● GORM Groovy Object Relational Mapping● Grails is able to understand the relationship

beetwen the classes and generate dinamically the user interface

● Now we want to change the type of the organizer in the class Event from String to Jug

● What we get is a long stacktrace

Page 58: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 58

We had to modify the code in the BootStraporganizer: Jug.findByName('JugPadova'),

This method is not coded, it is sinthetize using convention

Page 59: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 59

Dynamic Finders

Grails takes advantage of Groovy’s metaprogramming capabilities to synthesize finders for our domain class properties at runtime.

∗We can call methods that begin with findBy, findAllBy, or countBy, followed by up to two properties and optional operators.

Some examples will make this clearer. All of these would be valid methods on a Event instance:

• findAllByStartDateGreaterThan(new Date())

• findByLocationAndDescriptionLike("Verona", "%Day%")

Properties in dynamic finders can be joined by And or Or. The

following are some of the operators that can be used:

• LessThan

• Between

• IsNotNul

Page 60: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 60

● Now the application works● Simply defining an attribute of type Jug as a

property of the class Event Grails is able to understand the relationship between the classes

● We can go to the Event and Grails generate a link to the Jug

Page 61: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 61

Page 62: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 62

We need to add a method toString() to the class Jug

Page 63: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 63

Now we can add another domain class JugUser to model the volunteers that help to the realization of the eventWe create the controller with the scaffoldAnd we add a row to the class Eventstatic hasMany = [volunteers : JugUser]It is a Map

Page 64: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 64

We add some code to the BootStrap for adding some volunteers of type JugUser def g1 = Event.findByTitle( 'JavaDay 2009 Vr' )

g1.addToVolunteers(new JugUser(firstName: 'Tarin',

lastName: 'Gamberini',

email: '[email protected]'))

g1.addToVolunteers(new JugUser(firstName: 'Dario',

lastName: 'Santamaria',

email:' [email protected]'))

g1.save()

Page 65: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 65

Page 66: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 66

Relation One To Many

class Parent {...static hasMany = [children:Child]}class Child {...Parent parentstatic belongsTo = Parent}

Page 67: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 67

Validation

Constraints and ValidationConstraints are used in generating scaffolded views for a domain class as well as for hints in generating the database schema. But the real power of constraints is the part they play in validation. When we call save( ) or validate( ) on one of our domain class instances, Grails will try to validate the instance against any constraints we have assigned. If any of the constraints are not met, the save( ) or validate( ) call will fail, and appropriate error information will be stored in the instance’s errors property.∗

Page 68: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 68

● Grails provides several handy constraints that we can take advantage of, but it also gives us the ability to define custom constraints, so the possibilities are endless. Here are some of the more useful built-in constraints:

Page 69: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 69

blank (true/false): Allows an empty string value.nullable (true/false): Allows null values.max: Maximum value.min: Minimum value.maxSize: The maximum size of a String or Collection.minSize: The minimum size of a String or Collection.

Page 70: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 70

● inList: Value must be included in the supplied listv

● unique (true/false): Enforces uniqueness in the database.

● url (true/false): Value must be a valid URL.● email (true/false): Value must be a valid email

address.

Page 71: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 71

Anatomy of a controller

It's the time we can view the source codeWe can call the command grails generate-allThis command generate all the standard action in the controller and four standard views: create, edit, list and show.We can call the command with the parameter “*”

Page 72: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 72

class EventController { def index = { redirect(action:list,params:params) }● The first thing we see is the class declaration.

A Grails controller is a plain Groovy class. There is nothing to extend, and there are no interfaces to implement. Controllers serve as the entry points into a Grails application.

Page 73: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 73

The work done by a controller is done in an action. Actions are closure properties of the controller. Every closure declared in a controller is an action and can be accessed via a URL in the pattern: /appname/controllerBaseName/action. The first letter of the controller’s name will be lowercased, and the word Controller will be left off.

Page 74: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 74

There are three options to properly exit a controller action. We can call the render( ) method, which is added to all controllers and takes the name of a view along with a Map containing any data the view needs.We can call the redirect( ) method (which is also added to all controllers) to issue an HTTP redirect to another URL. And we can return null, or a Map containing data, which is referred to as a model.

Page 75: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 75

In this last case, Grails will attempt to render a view with the same name as the action. It will look for this view in a directory named after the root name of the controller; for example, returning from the list action of the EventController will cause Grails to render the view /JugEvents/views/event/list.gsp.

Page 76: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 76

● The first case of render, for example, is used on the action update

● The second case of redirect is used on the action index that redirects to the action list

● The third case is used on the action show, edit or create

Page 77: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 77

The index Action

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

Page 78: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 78

The list action

def list = { params.max = Math.min( params.max ? params.max.toInteger() : 10, 100) [ eventInstanceList: Event.list( params ), eventInstanceTotal: Event.count() ] }If parameter with the name max not exists it will add to params with the default value 10, then the function Math.min get the minimum between current value of max and 100

Page 79: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 79

The Action List

The last two lines make up a single statement that declares and returns a Map with two elements: eventInstanceList and eventInstanceTotal.The eventInstanceList is being loaded with a call to Event.list( ).The list( ) is being passed the params map, from which it will pull any parameters that it can use.The eventInstanceTotal is loaded with Event.count( ).

Page 80: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 80

The Show Action

def show = {

def eventInstance = Event.get( params.id )

if(!eventInstance) {

flash.message = "Event not found with id ${params.id}"

redirect(action:list)

}

else { return [ eventInstance : eventInstance ] }

}

Page 81: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 81

The Show Action

The show action expects an id parameter. Since many of the scaffolded actions expect an id parameter, Grails provides a URL mapping that enables the id to be part of the URL.If a Event instance is found with the id passed in, it is returned in a Map with the key of eventInstance. Finally, the show action will render the show view.

Page 82: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 82

The Delete Action

We view for the very first time a explicit reference to the underlying layers Spring

Page 83: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 83

The Edit Action

● The edit action doesn’t do any editing itself: that’s left up to the update action. Instead, edit loads up the necessary data and passes it to the edit view. Except for the name (which determines the view rendered), the edit action is identical to the show action.

Page 84: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 84

The Update Action

Like earlier actions, update tries to retrieve a Event instance with the id parameter. In this case, the id will be coming from a hidden field in the edit view. If an instance is found, we perform some optimistic concurrency checking.If all that goes well, we come to a very interesting step.eventInstance.properties = params

Page 85: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 85

Using SiteMesh for a consistent look

We go to observe the generated code for the views

Grails also uses SiteMesh, the page decoration framework from OpenSymphony, to assist in the page layout. SiteMesh will merge each of our .gsp files into a file called main.gsp. This is what gives a consistent look to all of our pages, as we saw with the dynamic scaffolding.

Page 86: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 86

The Create View

<g:hasErrors bean="${eventInstance}">

<div class="errors">

<g:renderErrors bean="${eventInstance}" as="list" />

</div>

</g:hasErrors>

Page 87: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 87

Grails uses GSPs (Groovy Server Pages) to provide the templates for the views. If you’ve used JSPs (JavaServer Pages), you’ll recognize the familiar syntax. As the name suggests, the main difference between GSPs and JSPs is the use of Groovy instead of Java to provide scriptlets.

Page 88: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 88

The List View

<g:sortableColumn property="title" title="Title" />.... <g:each in="${eventInstanceList}" status="i" var="eventInstance"> <div class="paginateButtons">.... <g:paginate total="${eventInstanceTotal}" /> </div>

Page 89: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 89

Resources

http://www.grails.org

Page 90: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 90

● We can add a list of anonimous user● static hasMany = [volunteers:JugUser,

respondents:String]

Page 91: Introduction To Grails

Intro

duzi

one

a G

rails

© - JUG Padova, 2003-2009 Paolo Foletto 91

Informazioni sul JUG Padova

Sito Web:http://www.jugpadova.itMailing List:

http://groups.google.it/group/[email protected]

Persone di riferimentoLucio Benfante ([email protected])

Dario Santamaria ([email protected])Luigi De PizzolPaolo Foletto ([email protected])Tarin Gamberini