Grails Quick Start

Modified: 03/13/2008, Created: 10/29/2007

Get up and running a minimal web application using Grails.

The following concepts will be touched upon:

  • Create a web app using Grails
  • Create Domain Class
  • Create CRUD web pages for the Domain Class
  • Create initial data for "development" environment (using BootStrap.groovy)
  • How to change the port number that the web app runs upon
  • How to get a war file of your Gails app
  • Modify the default Layout of web pages using Sitemesh

Also see the official Grails Quick Start

Install Grails (on Windows)

  • Prerequisites: Java JDK is installed properly.
  • Download a binary version of Grails from http://www.grails.org/
  • Extract the file someplace like C:\dev\tools
  • Set GRAILS_HOME to the extracted Grails folder
  • Add GRAILS_HOME\bin to your PATH
    • Sample: Set up a batch file (or run the following commands in a DOS prompt)
      REM// set up Grails
      
      set DEV_TOOLS_DIR=C:\dev\tools
      
      set GRAILS_HOME=%DEV_TOOLS_DIR%\grails-1.0.2
      set PATH=%GRAILS_HOME%\bin;%PATH%
      

To Create and Run a Grails Web App

  • change directory into where you want to create the new Grails application.
  • To see a list of the grails commands, run the following command:
    grails help
    
  • To create a skeleton application, run the following command:
    grails create-app holidayminder
    

    Here is a list of the files and directories created:

    Fig. 1: Grails Web App Created Files and Directories
  • Optionally, if you use Eclipse IDE, you can import the Grails web app into Eclipse IDE.
  • Change directory into the grails app root directory that was created.
    cd holidayminder
    
  • Create a domain class that can be persisted into a database. For the domain class name, use camel case. The first letter can be either upper or lower case.
    grails create-domain-class holiday
    

    The above command created the files:

    grails-app/domain/Holiday.groovy
    test/integration/HolidayTests.groovy
    
  • Edit file grails-app/domain/Holiday.groovy

    from

    class Holiday { 
    
    }
    
    

    to be

    class Holiday { 
    
    static constraints = {
    
    name(blank: true, nullable: true)
    dateOfHoliday(blank: false, nullable: true)
    dateCreated(nullable: true)
    status(blank: false, inList: ['active', 'inactive'], nullable: true)
    }
    
    String name
    Date dateOfHoliday
    Date dateCreated
    String status
    
    String toString()
    {
    String strTemp = "Holiday: date: ${dateOfHoliday}; name: ${name}";
    
    return strTemp;
    }
    
    }
    
  • Grail's Convention for URL Mapping:
    • http://localhost:8080/webappname/CONTROLLER/ACTION/ID

      if an Id is involved

    • http://localhost:8080/webappname/CONTROLLER/ACTION

      if an Id is not involved

  • There are two ways to create CRUD (Create, Read, Update, Delete) controllers for your domain class.
    • A) Create a static CRUD controller and views given the domain class
      • To generate a static CRUD controller along with supporting view GSP pages, run the following command:
        grails generate-all holiday
        

        In the above command, holiday is the domain class name.

        This command will create the following files

        grails-app/controllers/HolidayController.groovy
        grails-app/views/holiday/create.gsp
        grails-app/views/holiday/edit.gsp
        grails-app/views/holiday/list.gsp
        grails-app/views/holiday/show.gsp
        
      • Or you could have run the following two commands instead:
        grails generate-controller holiday
        grails generate-views holiday
        
    • B) Create a dynamic (scaffolded) CRUD controller
      • Let's create a controller with a package name and dynamic scaffolding. To do this run the following commands:
        grails create-controller dbmaint.HolidayDb
        

        This created the following files:

        grails-app/controllers/dbmaint/HolidayDbController.groovy
        test/integration/dbmaint/HolidayDbControllerTests.groovy
        

        and the directory

        grails-app/views/holidayDb
        
      • Edit the file grails-app/controllers/HolidayDbController.groovy from
        package dbmaint
        
        class HolidayDbController {
        
            def index = { }
        }
        

        to be

        package dbmaint
        
        class HolidayDbController {
        
        def scaffold = Holiday
        
        }
        
  • To run the web application, run the following command:
    grails dev run-app
    
  • Point a web browser to http://localhost:8080/holidayminderFig. 2: Grails Web App Welcome Page
  • You can click on the controller names to reach the CRUD web pages.
  • As you create data using the web pages, the data will be saved in an in-memory HSQLDB database. The data will go away when the Grails web app is stopped.
  • To shutdown the web app, type Ctrl-C in the Grails app terminal window
  • To get rid of that big o Grails logo, edit the file grails-app/views/layout/main.gsp from
    <html>
        <head>
            <title><g:layoutTitle default="Grails" /></title>
            <link rel="stylesheet" href="${createLinkTo(dir:'css',file:'main.css')}" />
            <link rel="shortcut icon" href="${createLinkTo(dir:'images',file:'favicon.ico')}" type="image/x-icon" />
            <g:layoutHead />
            <g:javascript library="application" />                          
        </head>
        <body>
            <div id="spinner" class="spinner" style="display:none;">
                <img src="${createLinkTo(dir:'images',file:'spinner.gif')}" alt="Spinner" />
            </div>  
            <div class="logo"><img src="${createLinkTo(dir:'images',file:'grails_logo.jpg')}" alt="Grails" /></div> 
            <g:layoutBody />                
        </body>     
    </html>
    

    to be

    <html>
        <head>
            <title><g:layoutTitle default="Grails" /></title>
            <link rel="stylesheet" href="${createLinkTo(dir:'css',file:'main.css')}" />
            <link rel="shortcut icon" href="${createLinkTo(dir:'images',file:'favicon.ico')}" type="image/x-icon" />
            <g:layoutHead />
            <g:javascript library="application" />                          
        </head>
        <body>
            <div id="spinner" class="spinner" style="display:none;">
                <img src="${createLinkTo(dir:'images',file:'spinner.gif')}" alt="Spinner" />
            </div>
    
            <div class="logo">
            <!--    
            <img src="${createLinkTo(dir:'images',file:'grails_logo.jpg')}" alt="Grails" />
            -->
            Grails Web App
            </div>
            
                    
            <g:layoutBody />                
        </body>     
    </html>
    
  • Now the web app looks like this.Fig. 3: Grails Web App Welcome Page

Load sample data at startup

  • Optional. To load sample data in the database at startup, you can add save commands in the file grails-app/conf/BootStrap.groovy .

    Edit the file grails-app/conf/BootStrap.groovy from

    class BootStrap {
    
         def init = { servletContext ->
         }
         def destroy = {
         }
    } 
    

    to be

    import grails.util.GrailsUtil
    
    class BootStrap
    {
    
    def init = { servletContext ->
    
    println "**** BootStrap; GrailsUtil.environment: ${GrailsUtil.environment}"
    
    switch (GrailsUtil.environment)
            {
            case "development":
                    println "**** BootStrap detected development"
               configureForDevelopment()
                    break
            case "test":
                    println "**** BootStrap detected test"
               configureForTest()
                    break
            case "production":
                    println "**** BootStrap detected production"
               configureForProduction()
                    break 
            }
    
    }
    
    def destroy = {
    
    }
    
    //---------------------------------------------------------
    /**
    Tasks to do when Grails in running in dev environment.
    
    */
    void configureForDevelopment()
    {
    println "BootStrap configureForDevelopment() called"
    
    def dataItem = new Holiday(name: "New Year's Day 2007", dateOfHoliday: new Date(), dateCreated: new Date(), status:"active")
    dataItem.save()
    (dataItem = new Holiday(name: "New Year's Day 2007", dateOfHoliday: new Date(), dateCreated: new Date(), status:"active")).save()
    (dataItem = new Holiday(name: "New Year's Day 2008", dateOfHoliday: new Date(), dateCreated: new Date(), status:"active")).save()
    (dataItem = new Holiday(name: "New Year's Day 2009", dateOfHoliday: new Date(), dateCreated: new Date(), status:"active")).save()
    
    }
    
    //---------------------------------------------------------
    void configureForTest()
    {
    println "BootStrap configureForTest() called"
    }
    
    //---------------------------------------------------------
    void configureForProduction()
    {
    println "BootStrap configureForProduction() called"
    }
    
    }
    

To change the port number of the Grails web server

Grails / Jetty runs on port 8080 by default. This is also the same default port number as Tomcat.

There are at least two ways to change the port number of the Grails (Jetty) web server.

Method 1

Edit the file GRAILS_HOME/scripts/Init.groovy and change the phrase 8080 to another port number like 9090 .

Method 2

When running the Grails web app, add a command line parameter of -Dserver.port=9090 before the run-app phrase.

Example:

grails -Dserver.port=9090 run-app
  • Now your web app will be reachable from the URL:
    http://localhost:9090/holidayminder
    

To get a war file of your Gails app

To get a war file of your Gails app configured to use development environment, run the command

grails dev war

The war file will be located in the root of your project.

To get a war file of your Gails app configured to use the production environment, run the command

grails war

The war file will be located in the root of your project.