SlideShare une entreprise Scribd logo
1  sur  91
Télécharger pour lire hors ligne
INTRODUZIONE A GRAILS
     a cura di Paolo Foletto
An Introduction to Grails
Introduzione a Grails




                        Learning by example
                        developing a web application
                        JugEvents using Netbeans

                        © - JUG Padova, 2003-2009 Paolo Foletto   2
Introduzione a Grails                                             Why this presentation?




                        paolo.foletto@jugpadova.it




                        © - JUG Padova, 2003-2009 Paolo Foletto                            3
Index of presentation




                         1)Motivations for Grails
Introduzione a Grails




                         2)Instructions for installation
                         3)MVC
                         4)Groovy
                         5)Dinamic scaffold
                         6)GORM Object Relational Mapping
                         7)Controller and views

                        © - JUG Padova, 2003-2009 Paolo Foletto                           4
What's is specific in this in this introduction?
Introduzione a Grails




                        Very easy e simple,
                        Quick start
                        beginners with no Java knowledge :)
                        Creating a very simple web application with
                        persistent data without learning using a
                        database?


                        © - JUG Padova, 2003-2009 Paolo Foletto            5
Introduzione a Grails                                             Can you ...




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




                        © - JUG Padova, 2003-2009 Paolo Foletto                 6
What is Grails?


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




                        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.

                        © - JUG Padova, 2003-2009 Paolo Foletto                     7
Why you should consider Grails?




                         1)Extremely simplified and speedy development
Introduzione a Grails




                         2)Ready to run
                         3)Great templating, Custom Tags


                        Java compatibility :) Spring based ;)



                        © - JUG Padova, 2003-2009 Paolo Foletto                       8
SpringSource -
                        Weapons for the War
Introduzione a Grails




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


                        © - JUG Padova, 2003-2009 Paolo Foletto   9
Introduzione a Grails                                             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.
                        © - JUG Padova, 2003-2009 Paolo Foletto                   10
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
Introduzione a Grails




                        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?

                        © - JUG Padova, 2003-2009 Paolo Foletto                              11
Ready to run




                        With Grails (1.x) you get an server and a db
                        ready to run.
Introduzione a Grails




                        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


                        © - JUG Padova, 2003-2009 Paolo Foletto                  12
Introduzione a Grails                                             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.




                        © - JUG Padova, 2003-2009 Paolo Foletto                                   13
Why the name Grails ?



                        Inspired by Ruby On Rails
Introduzione a Grails




                        Convention Over Configuration
                        DRY Don't Repeat Yourself
                        Exploits the power of Groovy
                        Three environment development, test and
                        production
                        Full stack of MVC ( Model View Controller)
                        Framework for Web Application

                        © - JUG Padova, 2003-2009 Paolo Foletto                           14
What you need to know to start?




                        The information you need to know is:
Introduzione a Grails




                        there is a good architecture in which
                        everything go easily to the right place
                        Much 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.




                        © - JUG Padova, 2003-2009 Paolo Foletto                                     15
Groovy




                        Groovy is an agile and dynamic language for the
                        Java Virtual Machine
Introduzione a Grails




                        makes modern programming features available to Java
                        developers with almost-zero learning curve
                        seamlessly integrates with all existing Java objects and
                        libraries
                        Increases developer productivity by reducing scaffolding
                        code when developing web, GUI, database or console
                        applications


                        © - JUG Padova, 2003-2009 Paolo Foletto                  16
Groovy Syntax Compared to Java




                            The first thing you’ll notice in a block of Groovy
Introduzione a Grails




                        ●

                            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.




                        © - JUG Padova, 2003-2009 Paolo Foletto                                    17
Groovy Syntax Compared to Java




                            Methods without arguments need the
Introduzione a Grails




                        ●

                            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.




                        © - JUG Padova, 2003-2009 Paolo Foletto                                    18
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
Introduzione a Grails




                            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.

                        © - JUG Padova, 2003-2009 Paolo Foletto                    19
def firstName = “Paolo”
Introduzione a Grails




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




                        © - JUG Padova, 2003-2009 Paolo Foletto            20
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.
Introduzione a Grails




                        Also the variables that are in the scope of the
                        definition of the closure are available to the
                        closure
                        Closure can take parameters explicit and implicit
                        def c = {a, b -> a + b}
                        it is the name of implicit parameter

                        © - JUG Padova, 2003-2009 Paolo Foletto                     21
def name = 'Lucio'
                        def c = {println "$name called this closure ${it+1}
                        time${it > 0 ? 's' : ' ' }"}
Introduzione a Grails




                        assert c instanceof Closure
                        4.times(c)


                        Lucio called this closure 1 time
                        Lucio called this closure 2 times
                        Lucio called this closure 3 times
                        Lucio called this closure 4 times
                        © - JUG Padova, 2003-2009 Paolo Foletto           22
1.The variable name is available when the
                          closure is executed.
Introduzione a Grails




                        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.


                        © - JUG Padova, 2003-2009 Paolo Foletto               23
Introduzione a Grails




                        ●   What would be in Java System.out.println( ) is
                            now just println( ).
                        ●   The method times passes an integer as
                            implicit parameter




                        © - JUG Padova, 2003-2009 Paolo Foletto              24
Getting Started




                        And now we start with the installation, assuming
                        that Java is already installed ...
Introduzione a Grails




                        Download and unzip grails.zip from the Grails
                        About 33 Mb for the version 1.1.1
                        site: www.Grails.org
                        Set GRAILS_HOME environment variables
                        Add to $GRAILS_HOME/bin to the path


                        © - JUG Padova, 2003-2009 Paolo Foletto                     25
Grails and NetBeans




                        Excellent support for Grails in NetBeans
Introduzione a Grails




                        Creating project
                        Running project
                        Running browser
                        Command grails
                        Installing plugin



                        © - JUG Padova, 2003-2009 Paolo Foletto                         26
Download ad install NetBeans




                        After install Grails, download and install the
                        lastest version of NetBeans, at the moment the
Introduzione a Grails




                        released version is 6.7.1
                        If you have a JDK installed you can dowload a
                        bundle.




                        © - JUG Padova, 2003-2009 Paolo Foletto                                  27
Getting Started




                        Create an application “MyFirstProject”
                        Run “grails create-app MyFirstProject”
Introduzione a Grails




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


                        © - JUG Padova, 2003-2009 Paolo Foletto                     28
MVC (Model View Controller)

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




                        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.

                        © - JUG Padova, 2003-2009 Paolo Foletto                           29
Domain Classes




                        The “Model”
Introduzione a Grails




                        Stick to the rules :
                        Let the controller do the controlling
                        Let the view do the viewing
                        May define validation constraints



                        © - JUG Padova, 2003-2009 Paolo Foletto                    30
Grails treats the domain classes as the
                        central and most important component of the
Introduzione a Grails




                        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.)


                        © - JUG Padova, 2003-2009 Paolo Foletto         31
Views




                        The Views
                        Groovy Server Pages (GSP)
Introduzione a Grails




                             –   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 view
                        Custom tag libraries


                        © - JUG Padova, 2003-2009 Paolo Foletto                    32
One FAQ from Grails Site

                         View Technologies
                         Q: 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
Introduzione a Grails




                         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.
                        © - JUG Padova, 2003-2009 Paolo Foletto                              33
Convention on the name of the URL



                        http://localhost:8080/jugevents/event/
                        http://localhost:8080/jugevents/event/create
Introduzione a Grails




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


                        Application context
                        Controller
                        Action ( optional) (default = 'index')
                        Record ID (optional)

                        © - JUG Padova, 2003-2009 Paolo Foletto                                       34
Grails then looks for a component specifying
                        the action to invoke within the given
                        controller. If the URL includes the action,
Introduzione a Grails




                        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

                        © - JUG Padova, 2003-2009 Paolo Foletto           35
Introduzione a Grails                                             Scaffolding




                        Dynamic and generated code
                        The generated code easy to learn




                        © - JUG Padova, 2003-2009 Paolo Foletto                 36
Introduzione a Grails




                        ●   An example application: JugEvents :)




                        © - JUG Padova, 2003-2009 Paolo Foletto    37
Introduzione a Grails




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

                        © - JUG Padova, 2003-2009 Paolo Foletto                 38
●   We can observe the
                                                                      structure of the
                                                                      directories that was
                                                                      created by the
Introduzione a Grails




                                                                      command
                                                                  ●   The command is a
                                                                      script groovy
                                                                  ●   We are interested in
                                                                      –   Domain classes
                                                                      –   Controllers
                                                                      –   Views and Layouts
                        © - JUG Padova, 2003-2009 Paolo Foletto                               39
We check the content of the directory
Introduzione a Grails




                        There is something in
                        ●   Configuration
                        ●   Message Bundles
                        ●   Web application



                        © - JUG Padova, 2003-2009 Paolo Foletto   40
Grails treats the domain classes as the
                        central and most important component of the
Introduzione a Grails




                        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.)


                        © - JUG Padova, 2003-2009 Paolo Foletto         41
Domain Class Event

                        $ grails create-domain-class Event
                        And then we add some properties


                        String title
Introduzione a Grails




                        Date startDate
                        Date endDate
                        String location
                        String directions
                        String description
                        String organizer
                        Date creationDate


                        © - JUG Padova, 2003-2009 Paolo Foletto                        42
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
Introduzione a Grails




                        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.

                        © - JUG Padova, 2003-2009 Paolo Foletto                          43
Introduzione a Grails                                             Domain Class Event




                        © - JUG Padova, 2003-2009 Paolo Foletto                        44
Introduzione a Grails                                      Convention on the name of the controller




                        © - JUG Padova, 2003-2009 Paolo Foletto                                        45
●   Create a controller
                        ●   Create a single method scaffold of one line
Introduzione a Grails




                        ●   And start the application
                        ●   NetBeans gentle starts the browser
                        ●   Select the event controller
                        ●   Create a new event
                        ●   Observe the result and the convention


                        © - JUG Padova, 2003-2009 Paolo Foletto           46
http://localhost:8080/jugevents/event/
Introduzione a Grails




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


                        Convention on the name of the
                        controller, action, id



                        © - JUG Padova, 2003-2009 Paolo Foletto        47
Introduzione a Grails




                        What we can see? And what not? Where is title?
                        Sortable columns
                        Link to the new item
                        © - JUG Padova, 2003-2009 Paolo Foletto          48
Introduzione a Grails




                        ●   Creating an event, title there is
                        © - JUG Padova, 2003-2009 Paolo Foletto   49
●   We can add some constraints to modify the
                            order of the fields , we edit the Event class
Introduzione a Grails




                        © - JUG Padova, 2003-2009 Paolo Foletto             50
Change the order of the fields

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




                        © - JUG Padova, 2003-2009 Paolo Foletto                                    51
Dimension


                        description(maxSize:5000)
Introduzione a Grails




                        © - JUG Padova, 2003-2009 Paolo Foletto               52
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
Introduzione a Grails




                        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).
                        © - JUG Padova, 2003-2009 Paolo Foletto                   53
Bootstrap




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




                        ●   We can initialize some data
                            We 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.


                        © - JUG Padova, 2003-2009 Paolo Foletto                54
Introduzione a Grails




                        ●   Now we can add another Domain Class Jug




                        © - JUG Padova, 2003-2009 Paolo Foletto       55
Introduzione a Grails




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




                        © - JUG Padova, 2003-2009 Paolo Foletto            56
Model a relation One to One




                        ●   We want model a relation One to One
                        ●   GORM Groovy Object Relational Mapping
Introduzione a Grails




                        ●   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


                        © - JUG Padova, 2003-2009 Paolo Foletto                                 57
We had to modify the code in the BootStrap
                        organizer: Jug.findByName('JugPadova'),
Introduzione a Grails




                        This method is not coded, it is sinthetize using
                        convention




                        © - JUG Padova, 2003-2009 Paolo Foletto            58
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.
Introduzione a Grails




                        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



                        © - JUG Padova, 2003-2009 Paolo Foletto                                                59
●   Now the application works
Introduzione a Grails




                        ●   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



                        © - JUG Padova, 2003-2009 Paolo Foletto             60
Introduzione a Grails




                        © - JUG Padova, 2003-2009 Paolo Foletto   61
We need to add a method toString() to the class Jug
Introduzione a Grails




                        © - JUG Padova, 2003-2009 Paolo Foletto               62
Now we can add another domain class JugUser
                        to model the volunteers that help to the
Introduzione a Grails




                        realization of the event
                        We create the controller with the scaffold
                        And we add a row to the class Event
                        static hasMany = [volunteers : JugUser]
                        It is a Map


                        © - JUG Padova, 2003-2009 Paolo Foletto       63
We add some code to the BootStrap for adding
                        some volunteers of type JugUser
                              def g1 = Event.findByTitle( 'JavaDay 2009 Vr' )
Introduzione a Grails




                              g1.addToVolunteers(new JugUser(firstName: 'Tarin',
                                      lastName: 'Gamberini',
                                      email: 'tarin.gamberini@jugpadova.it'))
                              g1.addToVolunteers(new JugUser(firstName: 'Dario',
                                      lastName: 'Santamaria',
                                      email:' dario.santamaria@jugpadova.it'))
                              g1.save()


                        © - JUG Padova, 2003-2009 Paolo Foletto                    64
Introduzione a Grails




                        © - JUG Padova, 2003-2009 Paolo Foletto   65
Relation One To Many


                        class Parent {
                        ...
                        static hasMany = [children:Child]
Introduzione a Grails




                        }
                        class Child {
                        ...
                        Parent parent
                        static belongsTo = Parent
                        }
                        © - JUG Padova, 2003-2009 Paolo Foletto                          66
Validation


                        Constraints and Validation
                        Constraints are used in generating scaffolded
                        views for a domain class as well as for hints in
Introduzione a Grails




                        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.
                        © - JUG Padova, 2003-2009 Paolo Foletto                   67
Introduzione a Grails




                        ●   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:




                        © - JUG Padova, 2003-2009 Paolo Foletto           68
blank (true/false): Allows an empty string value.
                        nullable (true/false): Allows null values.
Introduzione a Grails




                        max: Maximum value.
                        min: Minimum value.
                        maxSize: The maximum size of a String or
                        Collection.
                        minSize: The minimum size of a String or
                        Collection.


                        © - JUG Padova, 2003-2009 Paolo Foletto             69
●   inList: Value must be included in the supplied
                            listv
Introduzione a Grails




                        ●   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.



                        © - JUG Padova, 2003-2009 Paolo Foletto               70
Anatomy of a controller




                        It's the time we can view the source code
Introduzione a Grails




                        We can call the command grails generate-all
                        This 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 “*”



                        © - JUG Padova, 2003-2009 Paolo Foletto                             71
class EventController {
Introduzione a Grails




                           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.

                        © - JUG Padova, 2003-2009 Paolo Foletto               72
The work done by a controller is done in an
                        action. Actions are closure properties of the
                        controller. Every closure declared in a
Introduzione a Grails




                        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.



                        © - JUG Padova, 2003-2009 Paolo Foletto         73
There are three options to properly exit a
                          controller action. We can call the render( )
                          method, which is added to all controllers and
Introduzione a Grails




                          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.



                        © - JUG Padova, 2003-2009 Paolo Foletto          74
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
Introduzione a Grails




                         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.




                        © - JUG Padova, 2003-2009 Paolo Foletto               75
●   The first case of render, for example, is used
Introduzione a Grails




                            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



                        © - JUG Padova, 2003-2009 Paolo Foletto              76
Introduzione a Grails                                             The index Action




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




                        © - JUG Padova, 2003-2009 Paolo Foletto                      77
The list action


                        def list = {
                            params.max = Math.min( params.max ?
                        params.max.toInteger() : 10, 100)
Introduzione a Grails




                            [ 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

                        © - JUG Padova, 2003-2009 Paolo Foletto                     78
The Action List


                         The last two lines make up a single statement
                         that declares and returns a Map with two
                         elements: eventInstanceList and
Introduzione a Grails




                         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( ).



                        © - JUG Padova, 2003-2009 Paolo Foletto                     79
The Show Action




                        def show = {
                              def eventInstance = Event.get( params.id )
Introduzione a Grails




                              if(!eventInstance) {
                                  flash.message = "Event not found with id ${params.id}"
                                  redirect(action:list)
                              }
                              else { return [ eventInstance : eventInstance ] }
                          }



                        © - JUG Padova, 2003-2009 Paolo Foletto                            80
The Show Action




                        The show action expects an id parameter. Since
                        many of the scaffolded actions expect an id
Introduzione a Grails




                        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.



                        © - JUG Padova, 2003-2009 Paolo Foletto                     81
Introduzione a Grails                                             The Delete Action




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




                        © - JUG Padova, 2003-2009 Paolo Foletto                       82
The Edit Action




                            The edit action doesn’t do any editing itself:
Introduzione a Grails




                        ●

                            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.




                        © - JUG Padova, 2003-2009 Paolo Foletto                     83
The Update Action




                        Like earlier actions, update tries to retrieve a
                        Event instance with the id parameter. In this
Introduzione a Grails




                        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


                        © - JUG Padova, 2003-2009 Paolo Foletto                       84
Using SiteMesh for a consistent look




                        We go to observe the generated code for the
                        views
Introduzione a Grails




                        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.


                        © - JUG Padova, 2003-2009 Paolo Foletto                                          85
The Create View




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




                        <div class="errors">
                         <g:renderErrors bean="${eventInstance}" as="list" />
                        </div>
                        </g:hasErrors>




                        © - JUG Padova, 2003-2009 Paolo Foletto                     86
Grails uses GSPs (Groovy Server Pages) to
Introduzione a Grails




                        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.



                        © - JUG Padova, 2003-2009 Paolo Foletto          87
The List View




                         <g:sortableColumn property="title" title="Title" />
                        ....
Introduzione a Grails




                         <g:each in="${eventInstanceList}" status="i"
                        var="eventInstance">
                                      <div class="paginateButtons">
                        ....
                                  <g:paginate total="$
                        {eventInstanceTotal}" />
                                      </div>
                        © - JUG Padova, 2003-2009 Paolo Foletto                   88
Introduzione a Grails                                             Resources




                        http://www.grails.org




                        © - JUG Padova, 2003-2009 Paolo Foletto               89
Introduzione a Grails




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




                        © - JUG Padova, 2003-2009 Paolo Foletto     90
Informazioni sul JUG Padova


                        Sito Web:
                        http://www.jugpadova.it
                        Mailing List:
Introduzione a Grails




                             http://groups.google.it/group/jugpadova
                             jugpadova@googlegroups.com
                        Persone di riferimento
                        Lucio Benfante (lucio.benfante@jugpadova.it)
                             Dario Santamaria (dario.santamaria@jugpadova.it)
                             Luigi De Pizzol
                             Paolo Foletto (paolo.foletto@jugpadova.it)
                             Tarin Gamberini

                        © - JUG Padova, 2003-2009 Paolo Foletto                                 91

Contenu connexe

En vedette

Beating digital distractions
Beating digital distractionsBeating digital distractions
Beating digital distractionsscharrlibrary
 
LifeHackDay 2016 - Odessa: Катерина Дегтяр, 1991
LifeHackDay 2016 - Odessa: Катерина Дегтяр, 1991LifeHackDay 2016 - Odessa: Катерина Дегтяр, 1991
LifeHackDay 2016 - Odessa: Катерина Дегтяр, 1991Sergey Dovgopolyy
 
Copyright eab 11 21 2014
Copyright eab 11 21 2014Copyright eab 11 21 2014
Copyright eab 11 21 2014Elizabeth Brown
 
Lithium-ion Batteries for Hybrid and All-Electric Vehicles: the U.S. Value Ch...
Lithium-ion Batteries for Hybrid and All-Electric Vehicles: the U.S. Value Ch...Lithium-ion Batteries for Hybrid and All-Electric Vehicles: the U.S. Value Ch...
Lithium-ion Batteries for Hybrid and All-Electric Vehicles: the U.S. Value Ch...Andrew Gelston
 
Phantom International #FlyingPhantom 2016 Catalogue
Phantom International #FlyingPhantom 2016 CataloguePhantom International #FlyingPhantom 2016 Catalogue
Phantom International #FlyingPhantom 2016 CataloguePhantom International
 
Trastorno antisocial
Trastorno antisocialTrastorno antisocial
Trastorno antisocialluchimesa
 
九毛錢的大愛--創世基金會創辦人曹慶最近的故事
九毛錢的大愛--創世基金會創辦人曹慶最近的故事九毛錢的大愛--創世基金會創辦人曹慶最近的故事
九毛錢的大愛--創世基金會創辦人曹慶最近的故事seatof
 
Explorations in Cooperative Distributed Systems with Uber's Ringpop
Explorations in Cooperative Distributed Systems with Uber's RingpopExplorations in Cooperative Distributed Systems with Uber's Ringpop
Explorations in Cooperative Distributed Systems with Uber's Ringpopicemobile
 
Fuuny Body
Fuuny BodyFuuny Body
Fuuny Bodyeitkan
 
Business of Inbound tour operators at a glance
Business of Inbound tour operators at a glanceBusiness of Inbound tour operators at a glance
Business of Inbound tour operators at a glanceDoanh Tưng Tửng
 

En vedette (17)

Zaragoza turismo-54
Zaragoza turismo-54Zaragoza turismo-54
Zaragoza turismo-54
 
Beating digital distractions
Beating digital distractionsBeating digital distractions
Beating digital distractions
 
LifeHackDay 2016 - Odessa: Катерина Дегтяр, 1991
LifeHackDay 2016 - Odessa: Катерина Дегтяр, 1991LifeHackDay 2016 - Odessa: Катерина Дегтяр, 1991
LifeHackDay 2016 - Odessa: Катерина Дегтяр, 1991
 
QA lead
QA leadQA lead
QA lead
 
Copyright eab 11 21 2014
Copyright eab 11 21 2014Copyright eab 11 21 2014
Copyright eab 11 21 2014
 
Rock time hits
Rock time hitsRock time hits
Rock time hits
 
La WEB 2.0
La WEB 2.0 La WEB 2.0
La WEB 2.0
 
Lithium-ion Batteries for Hybrid and All-Electric Vehicles: the U.S. Value Ch...
Lithium-ion Batteries for Hybrid and All-Electric Vehicles: the U.S. Value Ch...Lithium-ion Batteries for Hybrid and All-Electric Vehicles: the U.S. Value Ch...
Lithium-ion Batteries for Hybrid and All-Electric Vehicles: the U.S. Value Ch...
 
Phantom International #FlyingPhantom 2016 Catalogue
Phantom International #FlyingPhantom 2016 CataloguePhantom International #FlyingPhantom 2016 Catalogue
Phantom International #FlyingPhantom 2016 Catalogue
 
Startup Manifesto
Startup ManifestoStartup Manifesto
Startup Manifesto
 
Designing Design Teams
Designing Design TeamsDesigning Design Teams
Designing Design Teams
 
Zaragoza turismo-46
Zaragoza turismo-46Zaragoza turismo-46
Zaragoza turismo-46
 
Trastorno antisocial
Trastorno antisocialTrastorno antisocial
Trastorno antisocial
 
九毛錢的大愛--創世基金會創辦人曹慶最近的故事
九毛錢的大愛--創世基金會創辦人曹慶最近的故事九毛錢的大愛--創世基金會創辦人曹慶最近的故事
九毛錢的大愛--創世基金會創辦人曹慶最近的故事
 
Explorations in Cooperative Distributed Systems with Uber's Ringpop
Explorations in Cooperative Distributed Systems with Uber's RingpopExplorations in Cooperative Distributed Systems with Uber's Ringpop
Explorations in Cooperative Distributed Systems with Uber's Ringpop
 
Fuuny Body
Fuuny BodyFuuny Body
Fuuny Body
 
Business of Inbound tour operators at a glance
Business of Inbound tour operators at a glanceBusiness of Inbound tour operators at a glance
Business of Inbound tour operators at a glance
 

Similaire à Introduction To Grails

Curious Coders Java Web Frameworks Comparison
Curious Coders Java Web Frameworks ComparisonCurious Coders Java Web Frameworks Comparison
Curious Coders Java Web Frameworks ComparisonHamed Hatami
 
Groovy introduction
Groovy introductionGroovy introduction
Groovy introductiongpottepalem
 
How and why GraalVM is quickly becoming relevant for you (DOAG 2020)
How and why GraalVM is quickly becoming relevant for you (DOAG 2020)How and why GraalVM is quickly becoming relevant for you (DOAG 2020)
How and why GraalVM is quickly becoming relevant for you (DOAG 2020)Lucas Jellema
 
Magic with groovy & grails
Magic with groovy & grailsMagic with groovy & grails
Magic with groovy & grailsGeorge Platon
 
Introduction To Groovy And Grails - SpringPeople
Introduction To Groovy And Grails - SpringPeopleIntroduction To Groovy And Grails - SpringPeople
Introduction To Groovy And Grails - SpringPeopleSpringPeople
 
What's Expected in Java 7
What's Expected in Java 7What's Expected in Java 7
What's Expected in Java 7Gal Marder
 
A path to modularity with Eclipse Virgo
A path to modularity with Eclipse VirgoA path to modularity with Eclipse Virgo
A path to modularity with Eclipse Virgokatya_todorova
 
Groovy Finesse
Groovy FinesseGroovy Finesse
Groovy Finessemzgubin
 
Groovy Finesse
Groovy FinesseGroovy Finesse
Groovy Finessemzgubin
 
Writing Domain-Specific Languages in Groovy
Writing Domain-Specific Languages in GroovyWriting Domain-Specific Languages in Groovy
Writing Domain-Specific Languages in GroovyGuillaume Laforge
 
The Grails introduction workshop
The Grails introduction workshopThe Grails introduction workshop
The Grails introduction workshopGR8Conf
 
6_PDFsam_DevOps.pdf
6_PDFsam_DevOps.pdf6_PDFsam_DevOps.pdf
6_PDFsam_DevOps.pdfmadhu291670
 
Top Reasons Why Java Rocks (report preview) - http:0t.ee/java-rocks
Top Reasons Why Java Rocks (report preview) - http:0t.ee/java-rocksTop Reasons Why Java Rocks (report preview) - http:0t.ee/java-rocks
Top Reasons Why Java Rocks (report preview) - http:0t.ee/java-rocksZeroTurnaround
 
Java Platform Tradeoffs (CEE SECR 2013)
Java Platform Tradeoffs (CEE SECR 2013)Java Platform Tradeoffs (CEE SECR 2013)
Java Platform Tradeoffs (CEE SECR 2013)Alexey Fyodorov
 
TechEvent Graal(VM) Performance Interoperability
TechEvent Graal(VM) Performance InteroperabilityTechEvent Graal(VM) Performance Interoperability
TechEvent Graal(VM) Performance InteroperabilityTrivadis
 
GROOVY ON GRAILS
GROOVY ON GRAILSGROOVY ON GRAILS
GROOVY ON GRAILSziyaaskerov
 

Similaire à Introduction To Grails (20)

Curious Coders Java Web Frameworks Comparison
Curious Coders Java Web Frameworks ComparisonCurious Coders Java Web Frameworks Comparison
Curious Coders Java Web Frameworks Comparison
 
Groovy & Grails
Groovy & GrailsGroovy & Grails
Groovy & Grails
 
Groovy introduction
Groovy introductionGroovy introduction
Groovy introduction
 
How and why GraalVM is quickly becoming relevant for you (DOAG 2020)
How and why GraalVM is quickly becoming relevant for you (DOAG 2020)How and why GraalVM is quickly becoming relevant for you (DOAG 2020)
How and why GraalVM is quickly becoming relevant for you (DOAG 2020)
 
Magic with groovy & grails
Magic with groovy & grailsMagic with groovy & grails
Magic with groovy & grails
 
Introduction To Groovy And Grails - SpringPeople
Introduction To Groovy And Grails - SpringPeopleIntroduction To Groovy And Grails - SpringPeople
Introduction To Groovy And Grails - SpringPeople
 
Whats New In Groovy 1.6?
Whats New In Groovy 1.6?Whats New In Groovy 1.6?
Whats New In Groovy 1.6?
 
What's Expected in Java 7
What's Expected in Java 7What's Expected in Java 7
What's Expected in Java 7
 
A path to modularity with Eclipse Virgo
A path to modularity with Eclipse VirgoA path to modularity with Eclipse Virgo
A path to modularity with Eclipse Virgo
 
Groovy Finesse
Groovy FinesseGroovy Finesse
Groovy Finesse
 
Groovy Finesse
Groovy FinesseGroovy Finesse
Groovy Finesse
 
Writing Domain-Specific Languages in Groovy
Writing Domain-Specific Languages in GroovyWriting Domain-Specific Languages in Groovy
Writing Domain-Specific Languages in Groovy
 
The Grails introduction workshop
The Grails introduction workshopThe Grails introduction workshop
The Grails introduction workshop
 
6_PDFsam_DevOps.pdf
6_PDFsam_DevOps.pdf6_PDFsam_DevOps.pdf
6_PDFsam_DevOps.pdf
 
Top Reasons Why Java Rocks (report preview) - http:0t.ee/java-rocks
Top Reasons Why Java Rocks (report preview) - http:0t.ee/java-rocksTop Reasons Why Java Rocks (report preview) - http:0t.ee/java-rocks
Top Reasons Why Java Rocks (report preview) - http:0t.ee/java-rocks
 
Java Platform Tradeoffs (CEE SECR 2013)
Java Platform Tradeoffs (CEE SECR 2013)Java Platform Tradeoffs (CEE SECR 2013)
Java Platform Tradeoffs (CEE SECR 2013)
 
Modularization in java 8
Modularization in java 8Modularization in java 8
Modularization in java 8
 
TechEvent Graal(VM) Performance Interoperability
TechEvent Graal(VM) Performance InteroperabilityTechEvent Graal(VM) Performance Interoperability
TechEvent Graal(VM) Performance Interoperability
 
GROOVY ON GRAILS
GROOVY ON GRAILSGROOVY ON GRAILS
GROOVY ON GRAILS
 
Gradle
GradleGradle
Gradle
 

Dernier

Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Dernier (20)

Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

Introduction To Grails

  • 1. INTRODUZIONE A GRAILS a cura di Paolo Foletto
  • 2. An Introduction to Grails Introduzione a Grails Learning by example developing a web application JugEvents using Netbeans © - JUG Padova, 2003-2009 Paolo Foletto 2
  • 3. Introduzione a Grails Why this presentation? paolo.foletto@jugpadova.it © - JUG Padova, 2003-2009 Paolo Foletto 3
  • 4. Index of presentation 1)Motivations for Grails Introduzione a Grails 2)Instructions for installation 3)MVC 4)Groovy 5)Dinamic scaffold 6)GORM Object Relational Mapping 7)Controller and views © - JUG Padova, 2003-2009 Paolo Foletto 4
  • 5. What's is specific in this in this introduction? Introduzione a Grails Very easy e simple, Quick start beginners with no Java knowledge :) Creating a very simple web application with persistent data without learning using a database? © - JUG Padova, 2003-2009 Paolo Foletto 5
  • 6. Introduzione a Grails Can you ... Using a persistence system without knowing that it exists? You can! © - JUG Padova, 2003-2009 Paolo Foletto 6
  • 7. What is Grails? Grails is an open source web framework powered by the Groovy – language based on Java Virtual Machine. Introduzione a Grails 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. © - JUG Padova, 2003-2009 Paolo Foletto 7
  • 8. Why you should consider Grails? 1)Extremely simplified and speedy development Introduzione a Grails 2)Ready to run 3)Great templating, Custom Tags Java compatibility :) Spring based ;) © - JUG Padova, 2003-2009 Paolo Foletto 8
  • 9. SpringSource - Weapons for the War Introduzione a Grails on Java Complexity http://blog.springsource. com/2008/11/11/more- weapons-for-the-war- on-complexity- springsource-acquires- groovygrails-leader/ © - JUG Padova, 2003-2009 Paolo Foletto 9
  • 10. Introduzione a Grails 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. © - JUG Padova, 2003-2009 Paolo Foletto 10
  • 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 Introduzione a Grails 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? © - JUG Padova, 2003-2009 Paolo Foletto 11
  • 12. Ready to run With Grails (1.x) you get an server and a db ready to run. Introduzione a Grails 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 © - JUG Padova, 2003-2009 Paolo Foletto 12
  • 13. Introduzione a Grails 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. © - JUG Padova, 2003-2009 Paolo Foletto 13
  • 14. Why the name Grails ? Inspired by Ruby On Rails Introduzione a Grails Convention Over Configuration DRY Don't Repeat Yourself Exploits the power of Groovy Three environment development, test and production Full stack of MVC ( Model View Controller) Framework for Web Application © - JUG Padova, 2003-2009 Paolo Foletto 14
  • 15. What you need to know to start? The information you need to know is: Introduzione a Grails there is a good architecture in which everything go easily to the right place Much 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. © - JUG Padova, 2003-2009 Paolo Foletto 15
  • 16. Groovy Groovy is an agile and dynamic language for the Java Virtual Machine Introduzione a Grails makes modern programming features available to Java developers with almost-zero learning curve seamlessly integrates with all existing Java objects and libraries Increases developer productivity by reducing scaffolding code when developing web, GUI, database or console applications © - JUG Padova, 2003-2009 Paolo Foletto 16
  • 17. Groovy Syntax Compared to Java The first thing you’ll notice in a block of Groovy Introduzione a Grails ● 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. © - JUG Padova, 2003-2009 Paolo Foletto 17
  • 18. Groovy Syntax Compared to Java Methods without arguments need the Introduzione a Grails ● 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. © - JUG Padova, 2003-2009 Paolo Foletto 18
  • 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 Introduzione a Grails 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. © - JUG Padova, 2003-2009 Paolo Foletto 19
  • 20. def firstName = “Paolo” Introduzione a Grails def lastName = “Foletto” def groovyString = ''$firstName , $lastName” assert groovyString == 'Paolo , Foletto' def groovyString = ''${firstName} , ${lastName}” © - JUG Padova, 2003-2009 Paolo Foletto 20
  • 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. Introduzione a Grails Also the variables that are in the scope of the definition of the closure are available to the closure Closure can take parameters explicit and implicit def c = {a, b -> a + b} it is the name of implicit parameter © - JUG Padova, 2003-2009 Paolo Foletto 21
  • 22. def name = 'Lucio' def c = {println "$name called this closure ${it+1} time${it > 0 ? 's' : ' ' }"} Introduzione a Grails assert c instanceof Closure 4.times(c) Lucio called this closure 1 time Lucio called this closure 2 times Lucio called this closure 3 times Lucio called this closure 4 times © - JUG Padova, 2003-2009 Paolo Foletto 22
  • 23. 1.The variable name is available when the closure is executed. Introduzione a Grails 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. © - JUG Padova, 2003-2009 Paolo Foletto 23
  • 24. Introduzione a Grails ● What would be in Java System.out.println( ) is now just println( ). ● The method times passes an integer as implicit parameter © - JUG Padova, 2003-2009 Paolo Foletto 24
  • 25. Getting Started And now we start with the installation, assuming that Java is already installed ... Introduzione a Grails Download and unzip grails.zip from the Grails About 33 Mb for the version 1.1.1 site: www.Grails.org Set GRAILS_HOME environment variables Add to $GRAILS_HOME/bin to the path © - JUG Padova, 2003-2009 Paolo Foletto 25
  • 26. Grails and NetBeans Excellent support for Grails in NetBeans Introduzione a Grails Creating project Running project Running browser Command grails Installing plugin © - JUG Padova, 2003-2009 Paolo Foletto 26
  • 27. Download ad install NetBeans After install Grails, download and install the lastest version of NetBeans, at the moment the Introduzione a Grails released version is 6.7.1 If you have a JDK installed you can dowload a bundle. © - JUG Padova, 2003-2009 Paolo Foletto 27
  • 28. Getting Started Create an application “MyFirstProject” Run “grails create-app MyFirstProject” Introduzione a Grails Run “grails create-domain-class People” Edit people.grovy Run “grails generate-all” Run “grails run-http” © - JUG Padova, 2003-2009 Paolo Foletto 28
  • 29. MVC (Model View Controller) A design pattern used in services architectures. Contains 3 distinct elements : Introduzione a Grails 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. © - JUG Padova, 2003-2009 Paolo Foletto 29
  • 30. Domain Classes The “Model” Introduzione a Grails Stick to the rules : Let the controller do the controlling Let the view do the viewing May define validation constraints © - JUG Padova, 2003-2009 Paolo Foletto 30
  • 31. Grails treats the domain classes as the central and most important component of the Introduzione a Grails 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.) © - JUG Padova, 2003-2009 Paolo Foletto 31
  • 32. Views The Views Groovy Server Pages (GSP) Introduzione a Grails – 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 view Custom tag libraries © - JUG Padova, 2003-2009 Paolo Foletto 32
  • 33. One FAQ from Grails Site View Technologies Q: 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 Introduzione a Grails 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. © - JUG Padova, 2003-2009 Paolo Foletto 33
  • 34. Convention on the name of the URL http://localhost:8080/jugevents/event/ http://localhost:8080/jugevents/event/create Introduzione a Grails http://localhost:8080/jugevents/jug/show/1 Application context Controller Action ( optional) (default = 'index') Record ID (optional) © - JUG Padova, 2003-2009 Paolo Foletto 34
  • 35. Grails then looks for a component specifying the action to invoke within the given controller. If the URL includes the action, Introduzione a Grails 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 © - JUG Padova, 2003-2009 Paolo Foletto 35
  • 36. Introduzione a Grails Scaffolding Dynamic and generated code The generated code easy to learn © - JUG Padova, 2003-2009 Paolo Foletto 36
  • 37. Introduzione a Grails ● An example application: JugEvents :) © - JUG Padova, 2003-2009 Paolo Foletto 37
  • 38. Introduzione a Grails ● We start creating a new project, we choose a Grails application, the first time we had to configure where is installed Grails © - JUG Padova, 2003-2009 Paolo Foletto 38
  • 39. We can observe the structure of the directories that was created by the Introduzione a Grails command ● The command is a script groovy ● We are interested in – Domain classes – Controllers – Views and Layouts © - JUG Padova, 2003-2009 Paolo Foletto 39
  • 40. We check the content of the directory Introduzione a Grails There is something in ● Configuration ● Message Bundles ● Web application © - JUG Padova, 2003-2009 Paolo Foletto 40
  • 41. Grails treats the domain classes as the central and most important component of the Introduzione a Grails 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.) © - JUG Padova, 2003-2009 Paolo Foletto 41
  • 42. Domain Class Event $ grails create-domain-class Event And then we add some properties String title Introduzione a Grails Date startDate Date endDate String location String directions String description String organizer Date creationDate © - JUG Padova, 2003-2009 Paolo Foletto 42
  • 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 Introduzione a Grails 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. © - JUG Padova, 2003-2009 Paolo Foletto 43
  • 44. Introduzione a Grails Domain Class Event © - JUG Padova, 2003-2009 Paolo Foletto 44
  • 45. Introduzione a Grails  Convention on the name of the controller © - JUG Padova, 2003-2009 Paolo Foletto 45
  • 46. Create a controller ● Create a single method scaffold of one line Introduzione a Grails ● And start the application ● NetBeans gentle starts the browser ● Select the event controller ● Create a new event ● Observe the result and the convention © - JUG Padova, 2003-2009 Paolo Foletto 46
  • 47. http://localhost:8080/jugevents/event/ Introduzione a Grails http://localhost:8080/jugevents/event/create http://localhost:8080/jugevents/jug/show/1 Convention on the name of the controller, action, id © - JUG Padova, 2003-2009 Paolo Foletto 47
  • 48. Introduzione a Grails What we can see? And what not? Where is title? Sortable columns Link to the new item © - JUG Padova, 2003-2009 Paolo Foletto 48
  • 49. Introduzione a Grails ● Creating an event, title there is © - JUG Padova, 2003-2009 Paolo Foletto 49
  • 50. We can add some constraints to modify the order of the fields , we edit the Event class Introduzione a Grails © - JUG Padova, 2003-2009 Paolo Foletto 50
  • 51. Change the order of the fields ● By default Grails shows the first six fields in alfabetical order but we can change very easily Introduzione a Grails © - JUG Padova, 2003-2009 Paolo Foletto 51
  • 52. Dimension description(maxSize:5000) Introduzione a Grails © - JUG Padova, 2003-2009 Paolo Foletto 52
  • 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 Introduzione a Grails 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). © - JUG Padova, 2003-2009 Paolo Foletto 53
  • 54. Bootstrap ● The BootStrap.groovy has a method init that is executed at the bootstrap of the application Introduzione a Grails ● We can initialize some data We 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. © - JUG Padova, 2003-2009 Paolo Foletto 54
  • 55. Introduzione a Grails ● Now we can add another Domain Class Jug © - JUG Padova, 2003-2009 Paolo Foletto 55
  • 56. Introduzione a Grails ● Create a controller with the method scaffold ● Add a Jug in BootStrap ● Restart the application ● We have two controllers © - JUG Padova, 2003-2009 Paolo Foletto 56
  • 57. Model a relation One to One ● We want model a relation One to One ● GORM Groovy Object Relational Mapping Introduzione a Grails ● 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 © - JUG Padova, 2003-2009 Paolo Foletto 57
  • 58. We had to modify the code in the BootStrap organizer: Jug.findByName('JugPadova'), Introduzione a Grails This method is not coded, it is sinthetize using convention © - JUG Padova, 2003-2009 Paolo Foletto 58
  • 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. Introduzione a Grails 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 © - JUG Padova, 2003-2009 Paolo Foletto 59
  • 60. Now the application works Introduzione a Grails ● 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 © - JUG Padova, 2003-2009 Paolo Foletto 60
  • 61. Introduzione a Grails © - JUG Padova, 2003-2009 Paolo Foletto 61
  • 62. We need to add a method toString() to the class Jug Introduzione a Grails © - JUG Padova, 2003-2009 Paolo Foletto 62
  • 63. Now we can add another domain class JugUser to model the volunteers that help to the Introduzione a Grails realization of the event We create the controller with the scaffold And we add a row to the class Event static hasMany = [volunteers : JugUser] It is a Map © - JUG Padova, 2003-2009 Paolo Foletto 63
  • 64. We add some code to the BootStrap for adding some volunteers of type JugUser def g1 = Event.findByTitle( 'JavaDay 2009 Vr' ) Introduzione a Grails g1.addToVolunteers(new JugUser(firstName: 'Tarin', lastName: 'Gamberini', email: 'tarin.gamberini@jugpadova.it')) g1.addToVolunteers(new JugUser(firstName: 'Dario', lastName: 'Santamaria', email:' dario.santamaria@jugpadova.it')) g1.save() © - JUG Padova, 2003-2009 Paolo Foletto 64
  • 65. Introduzione a Grails © - JUG Padova, 2003-2009 Paolo Foletto 65
  • 66. Relation One To Many class Parent { ... static hasMany = [children:Child] Introduzione a Grails } class Child { ... Parent parent static belongsTo = Parent } © - JUG Padova, 2003-2009 Paolo Foletto 66
  • 67. Validation Constraints and Validation Constraints are used in generating scaffolded views for a domain class as well as for hints in Introduzione a Grails 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. © - JUG Padova, 2003-2009 Paolo Foletto 67
  • 68. Introduzione a Grails ● 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: © - JUG Padova, 2003-2009 Paolo Foletto 68
  • 69. blank (true/false): Allows an empty string value. nullable (true/false): Allows null values. Introduzione a Grails max: Maximum value. min: Minimum value. maxSize: The maximum size of a String or Collection. minSize: The minimum size of a String or Collection. © - JUG Padova, 2003-2009 Paolo Foletto 69
  • 70. inList: Value must be included in the supplied listv Introduzione a Grails ● 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. © - JUG Padova, 2003-2009 Paolo Foletto 70
  • 71. Anatomy of a controller It's the time we can view the source code Introduzione a Grails We can call the command grails generate-all This 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 “*” © - JUG Padova, 2003-2009 Paolo Foletto 71
  • 72. class EventController { Introduzione a Grails 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. © - JUG Padova, 2003-2009 Paolo Foletto 72
  • 73. The work done by a controller is done in an action. Actions are closure properties of the controller. Every closure declared in a Introduzione a Grails 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. © - JUG Padova, 2003-2009 Paolo Foletto 73
  • 74. There are three options to properly exit a controller action. We can call the render( ) method, which is added to all controllers and Introduzione a Grails 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. © - JUG Padova, 2003-2009 Paolo Foletto 74
  • 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 Introduzione a Grails 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. © - JUG Padova, 2003-2009 Paolo Foletto 75
  • 76. The first case of render, for example, is used Introduzione a Grails 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 © - JUG Padova, 2003-2009 Paolo Foletto 76
  • 77. Introduzione a Grails The index Action def index = { redirect(action:list,params:params) } © - JUG Padova, 2003-2009 Paolo Foletto 77
  • 78. The list action def list = { params.max = Math.min( params.max ? params.max.toInteger() : 10, 100) Introduzione a Grails [ 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 © - JUG Padova, 2003-2009 Paolo Foletto 78
  • 79. The Action List The last two lines make up a single statement that declares and returns a Map with two elements: eventInstanceList and Introduzione a Grails 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( ). © - JUG Padova, 2003-2009 Paolo Foletto 79
  • 80. The Show Action def show = { def eventInstance = Event.get( params.id ) Introduzione a Grails if(!eventInstance) { flash.message = "Event not found with id ${params.id}" redirect(action:list) } else { return [ eventInstance : eventInstance ] } } © - JUG Padova, 2003-2009 Paolo Foletto 80
  • 81. The Show Action The show action expects an id parameter. Since many of the scaffolded actions expect an id Introduzione a Grails 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. © - JUG Padova, 2003-2009 Paolo Foletto 81
  • 82. Introduzione a Grails The Delete Action We view for the very first time a explicit reference to the underlying layers Spring © - JUG Padova, 2003-2009 Paolo Foletto 82
  • 83. The Edit Action The edit action doesn’t do any editing itself: Introduzione a Grails ● 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. © - JUG Padova, 2003-2009 Paolo Foletto 83
  • 84. The Update Action Like earlier actions, update tries to retrieve a Event instance with the id parameter. In this Introduzione a Grails 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 © - JUG Padova, 2003-2009 Paolo Foletto 84
  • 85. Using SiteMesh for a consistent look We go to observe the generated code for the views Introduzione a Grails 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. © - JUG Padova, 2003-2009 Paolo Foletto 85
  • 86. The Create View <g:hasErrors bean="${eventInstance}"> Introduzione a Grails <div class="errors"> <g:renderErrors bean="${eventInstance}" as="list" /> </div> </g:hasErrors> © - JUG Padova, 2003-2009 Paolo Foletto 86
  • 87. Grails uses GSPs (Groovy Server Pages) to Introduzione a Grails 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. © - JUG Padova, 2003-2009 Paolo Foletto 87
  • 88. The List View <g:sortableColumn property="title" title="Title" /> .... Introduzione a Grails <g:each in="${eventInstanceList}" status="i" var="eventInstance"> <div class="paginateButtons"> .... <g:paginate total="$ {eventInstanceTotal}" /> </div> © - JUG Padova, 2003-2009 Paolo Foletto 88
  • 89. Introduzione a Grails Resources http://www.grails.org © - JUG Padova, 2003-2009 Paolo Foletto 89
  • 90. Introduzione a Grails ● We can add a list of anonimous user ● static hasMany = [volunteers:JugUser, respondents:String] © - JUG Padova, 2003-2009 Paolo Foletto 90
  • 91. Informazioni sul JUG Padova Sito Web: http://www.jugpadova.it Mailing List: Introduzione a Grails http://groups.google.it/group/jugpadova jugpadova@googlegroups.com Persone di riferimento Lucio Benfante (lucio.benfante@jugpadova.it) Dario Santamaria (dario.santamaria@jugpadova.it) Luigi De Pizzol Paolo Foletto (paolo.foletto@jugpadova.it) Tarin Gamberini © - JUG Padova, 2003-2009 Paolo Foletto 91