INTRODUZIONE A GRAILS
     a cura di Paolo Foletto
An Introduction to Grails
Introduzione a Grails




                        Learning by example
                        de...
Introduzione a Grails                                             Why this presentation?




                        paolo...
Index of presentation




                         1)Motivations for Grails
Introduzione a Grails




                    ...
What's is specific in this in this introduction?
Introduzione a Grails




                        Very easy e simple,
   ...
Introduzione a Grails                                             Can you ...




                        Using a persiste...
What is Grails?


                        Grails is an open source web framework powered by
                        the Gr...
Why you should consider Grails?




                         1)Extremely simplified and speedy development
Introduzione a ...
SpringSource -
                        Weapons for the War
Introduzione a Grails




                        on Java Compl...
Introduzione a Grails                                             Graeme Rocher




                        As Head of Gra...
Because it’s easy to start with


                        Grails offers an easy start for experienced Java
               ...
Ready to run




                        With Grails (1.x) you get an server and a db
                        ready to run...
Introduzione a Grails                                             Great templating, Custom Tags




                      ...
Why the name Grails ?



                        Inspired by Ruby On Rails
Introduzione a Grails




                     ...
What you need to know to start?




                        The information you need to know is:
Introduzione a Grails



...
Groovy




                        Groovy is an agile and dynamic language for the
                        Java Virtual Ma...
Groovy Syntax Compared to Java




                            The first thing you’ll notice in a block of Groovy
Introduzi...
Groovy Syntax Compared to Java




                            Methods without arguments need the
Introduzione a Grails


...
Groovy Strings


                        ●   Groovy adds a new string known as a GString.
                            A GS...
def firstName = “Paolo”
Introduzione a Grails




                        def lastName = “Foletto”
                       ...
Groovy Closures



                        A Groovy closure, in simple terms, is an
                        executable blo...
def name = 'Lucio'
                        def c = {println "$name called this closure ${it+1}
                        tim...
1.The variable name is available when the
                          closure is executed.
Introduzione a Grails




       ...
Introduzione a Grails




                        ●   What would be in Java System.out.println( ) is
                     ...
Getting Started




                        And now we start with the installation, assuming
                        that ...
Grails and NetBeans




                        Excellent support for Grails in NetBeans
Introduzione a Grails




       ...
Download ad install NetBeans




                        After install Grails, download and install the
                  ...
Getting Started




                        Create an application “MyFirstProject”
                        Run “grails cre...
MVC (Model View Controller)

                        A design pattern used in services
                        architectur...
Domain Classes




                        The “Model”
Introduzione a Grails




                        Stick to the rule...
Grails treats the domain classes as the
                        central and most important component of the
Introduzione a...
Views




                        The Views
                        Groovy Server Pages (GSP)
Introduzione a Grails




  ...
One FAQ from Grails Site

                         View Technologies
                         Q: When I point my browser a...
Convention on the name of the URL



                        http://localhost:8080/jugevents/event/
                      ...
Grails then looks for a component specifying
                        the action to invoke within the given
               ...
Introduzione a Grails                                             Scaffolding




                        Dynamic and gene...
Introduzione a Grails




                        ●   An example application: JugEvents :)




                        © -...
Introduzione a Grails




                             ●   We start creating a new project, we choose a
                  ...
●   We can observe the
                                                                      structure of the
            ...
We check the content of the directory
Introduzione a Grails




                        There is something in
            ...
Grails treats the domain classes as the
                        central and most important component of the
Introduzione a...
Domain Class Event

                        $ grails create-domain-class Event
                        And then we add som...
Before we move on to the controllers, notice for a moment
                        that there’s nothing in these classes th...
Introduzione a Grails                                             Domain Class Event




                        © - JUG P...
Introduzione a Grails                                      Convention on the name of the controller




                 ...
●   Create a controller
                        ●   Create a single method scaffold of one line
Introduzione a Grails




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




                        http://localhost:8080/jugevents/e...
Introduzione a Grails




                        What we can see? And what not? Where is title?
                        S...
Introduzione a Grails




                        ●   Creating an event, title there is
                        © - JUG Pa...
●   We can add some constraints to modify the
                            order of the fields , we edit the Event class
In...
Change the order of the fields

                        ●   By default Grails shows the first six fields in
              ...
Dimension


                        description(maxSize:5000)
Introduzione a Grails




                        © - JUG Pa...
The constraints consist of a code block, which is a
                        Groovy closure.
                        Inside...
Bootstrap




                        ●   The BootStrap.groovy has a method init that is
                            execu...
Introduzione a Grails




                        ●   Now we can add another Domain Class Jug




                        ...
Introduzione a Grails




                        ●   Create a controller with the method scaffold
                       ...
Model a relation One to One




                        ●   We want model a relation One to One
                        ● ...
We had to modify the code in the BootStrap
                        organizer: Jug.findByName('JugPadova'),
Introduzione a ...
Dynamic Finders


                        Grails takes advantage of Groovy’s metaprogramming capabilities to synthesize fin...
●   Now the application works
Introduzione a Grails




                        ●   Simply defining an attribute of type J...
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...
Now we can add another domain class JugUser
                        to model the volunteers that help to the
Introduzione ...
We add some code to the BootStrap for adding
                        some volunteers of type JugUser
                     ...
Introduzione a Grails




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


                        class Parent {
                        ...
                        static h...
Validation


                        Constraints and Validation
                        Constraints are used in generating...
Introduzione a Grails




                        ●   Grails provides several handy constraints that
                     ...
blank (true/false): Allows an empty string value.
                        nullable (true/false): Allows null values.
Intro...
●   inList: Value must be included in the supplied
                            listv
Introduzione a Grails




           ...
Anatomy of a controller




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




  ...
class EventController {
Introduzione a Grails




                           def index =
                        { redirec...
The work done by a controller is done in an
                        action. Actions are closure properties of the
        ...
There are three options to properly exit a
                          controller action. We can call the render( )
        ...
In this last case, Grails will attempt to render a
                         view with the same name as the action. It will...
●   The first case of render, for example, is used
Introduzione a Grails




                            on the action upd...
Introduzione a Grails                                             The index Action




                        def index =...
The list action


                        def list = {
                            params.max = Math.min( params.max ?
   ...
The Action List


                         The last two lines make up a single statement
                         that dec...
The Show Action




                        def show = {
                              def eventInstance = Event.get( para...
The Show Action




                        The show action expects an id parameter. Since
                        many of...
Introduzione a Grails                                             The Delete Action




                        We view fo...
The Edit Action




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




 ...
The Update Action




                        Like earlier actions, update tries to retrieve a
                        Eve...
Using SiteMesh for a consistent look




                        We go to observe the generated code for the
             ...
The Create View




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




              ...
Grails uses GSPs (Groovy Server Pages) to
Introduzione a Grails




                        provide the templates for the ...
The List View




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




                        http://www.grails....
Introduzione a Grails




                        ●   We can add a list of anonimous user
                        ●   stat...
Informazioni sul JUG Padova


                        Sito Web:
                        http://www.jugpadova.it
          ...
Upcoming SlideShare
Loading in...5
×

Introduction To Grails

3,230

Published on

Published in: Technology, Education
1 Comment
3 Likes
Statistics
Notes
No Downloads
Views
Total Views
3,230
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
83
Comments
1
Likes
3
Embeds 0
No embeds

No notes for slide

Transcript of "Introduction To Grails"

  1. 1. INTRODUZIONE A GRAILS a cura di Paolo Foletto
  2. 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. 3. Introduzione a Grails Why this presentation? paolo.foletto@jugpadova.it © - JUG Padova, 2003-2009 Paolo Foletto 3
  4. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 36. Introduzione a Grails Scaffolding Dynamic and generated code The generated code easy to learn © - JUG Padova, 2003-2009 Paolo Foletto 36
  37. 37. Introduzione a Grails ● An example application: JugEvents :) © - JUG Padova, 2003-2009 Paolo Foletto 37
  38. 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. 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. 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. 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. 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. 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. 44. Introduzione a Grails Domain Class Event © - JUG Padova, 2003-2009 Paolo Foletto 44
  45. 45. Introduzione a Grails  Convention on the name of the controller © - JUG Padova, 2003-2009 Paolo Foletto 45
  46. 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. 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. 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. 49. Introduzione a Grails ● Creating an event, title there is © - JUG Padova, 2003-2009 Paolo Foletto 49
  50. 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. 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. 52. Dimension description(maxSize:5000) Introduzione a Grails © - JUG Padova, 2003-2009 Paolo Foletto 52
  53. 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. 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. 55. Introduzione a Grails ● Now we can add another Domain Class Jug © - JUG Padova, 2003-2009 Paolo Foletto 55
  56. 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. 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. 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. 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. 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. 61. Introduzione a Grails © - JUG Padova, 2003-2009 Paolo Foletto 61
  62. 62. We need to add a method toString() to the class Jug Introduzione a Grails © - JUG Padova, 2003-2009 Paolo Foletto 62
  63. 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. 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. 65. Introduzione a Grails © - JUG Padova, 2003-2009 Paolo Foletto 65
  66. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 77. Introduzione a Grails The index Action def index = { redirect(action:list,params:params) } © - JUG Padova, 2003-2009 Paolo Foletto 77
  78. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 89. Introduzione a Grails Resources http://www.grails.org © - JUG Padova, 2003-2009 Paolo Foletto 89
  90. 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. 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
  1. Gostou de algum slide específico?

    Recortar slides é uma maneira fácil de colecionar informações para acessar mais tarde.

×