(Quick Reference)

2 Getting Started

Version: 6.2.3-SNAPSHOT

2 Getting Started

2.1 Installation Requirements

Before installing Grails you will need a Java Development Kit (JDK) installed with the minimum version denoted in the table below. Download the appropriate JDK for your operating system, run the installer, and then set up an environment variable called JAVA_HOME pointing to the location of this installation.

Grails version JDK version (minimum)

6

11

5

8

To automate the installation of Grails we recommend SDKMAN which greatly simplifies installing and managing multiple Grails versions.

On some platforms (for example macOS) the Java installation is automatically detected. However in many cases you will want to manually configure the location of Java. For example, if you’re using bash or another variant of the Bourne Shell:

export JAVA_HOME=/Library/Java/Home
export PATH="$PATH:$JAVA_HOME/bin"
On Windows you would have to configure these environment variables in My Computer/Advanced/Environment Variables

2.2 Downloading and Installing

The first step to getting up and running with Grails is to install the distribution.

The best way to install Grails on *nix systems is with SDKMAN which greatly simplifies installing and managing multiple Grails versions.

Install with SDKMAN

To install the latest version of Grails using SDKMAN, run this on your terminal:

$ sdk install grails

You can also specify a version

$ sdk install grails 6.2.3-SNAPSHOT

You can find more information about SDKMAN usage on the SDKMAN Docs

Manual installation

For manual installation follow these steps:

  • Download a binary distribution of Grails and extract the resulting zip file to a location of your choice

  • Set the GRAILS_HOME environment variable to the location where you extracted the zip

Unix/Linux

  • This is typically a matter of adding something like the following export GRAILS_HOME=/path/to/grails to your profile

  • This can be done by adding export PATH="$PATH:$GRAILS_HOME/bin" to your profile

Windows

  • Copy the path to the bin directory inside the grails folder you have downloaded, for example,

C:\path_to_grails\bin
  • Go to Environment Variables, you can typically search or run the command below, the type env and then Enter

Start + R
  • Edit the Path variable on User Variables / System Variables depending on your choice.

  • Paste the copied path in the Path Variable.

If Grails is working correctly you should now be able to type grails --version in the terminal window and see output similar to this:

Grails Version: 6.2.3-SNAPSHOT

2.3 Creating an Application

To create a Grails application you first need to familiarize yourself with the usage of the grails command which is used in the following manner:

$ grails <<command name>>

Run create-app to create an application:

$ grails create-app myapp

This will create a new directory inside the current one that contains the project. Navigate to this directory in your console:

$ cd myapp

2.4 Creating a Simple Web Application with Grails

Step 1: Create a New Project

Open your command prompt or terminal.

Navigate to the directory where you want to create your Grails project:

$ cd your_project_directory

Create a new Grails project with the following command:

$ grails create-app myapp

Step 2: Access the Project Directory

Change into the "myapp" directory, which you just created:

$ cd myapp

Step 3: Start Grails Interactive Console

Start the Grails interactive console by running the "grails" command:

$ grails

Step 4: Create a Controller

In the Grails interactive console, you can use auto-completion to create a controller. Type the following command to create a controller named "greeting":

grails> create-controller greeting

This command will generate a new controller named "GreetingController.groovy" within the grails-app/controllers/myapp directory. You might wonder why there is an additional "myapp" directory. This structure aligns with conventions commonly used in Java development, where classes are organized into packages. Grails automatically includes the application name as part of the package structure. If you do not specify a package, Grails defaults to using the application name.

For more detailed information on creating controllers, you can refer to the documentation on the create-controller page.

Step 5: Edit the Controller

Open the "GreetingController.groovy" file located in the "grails-app/controllers/myapp" directory in a text editor.

Add the following code to the "GreetingController.groovy" file:

package myapp

class GreetingController {

    def index() {
        render "Hello, Congratulations for your first Grails application!"
    }
}

The action is simply a method. In this particular case, it calls a special method provided by Grails to render the page.

Step 6: Run the Application

Grails framework now relies on Gradle tasks for running the application. To start the application, use the following Gradle bootRun command:

$ ./gradlew bootRun

Your application will be hosted on port 8080 by default. You can access it in your web browser at:

Now, it’s important to know that the welcome page is determined by the following URL mapping:

class UrlMappings {
    static mappings = {
        "/$controller/$action?/$id?(.$format)?"{
            constraints {
                // apply constraints here
            }
        }

        "/"(view:"/index")
        "500"(view:'/error')
        "404"(view:'/notFound')
    }
}

This mapping specifies that the root URL ("/") should display the "index.gsp" view, which is located at "grails-app/views/index.gsp." This "index.gsp" file serves as your welcome or landing page. The other entries in the mapping handle error pages for HTTP status codes 500 and 404.

Grails URL Convention Based on Controller and Action Name

Grails follows a URL convention that relies on the names of controllers and their actions. This convention simplifies the creation and access of various pages or functionalities within your web application.

In the provided code example:

package myapp

class GreetingController {

    def index() {
        render "Hello, Congratulations for your first Grails application!"
    }
}
  • The GreetingController class represents a controller in Grails.

  • Inside the controller, there’s an index action defined as a method. In Grails, actions are essentially methods within a controller that handle specific tasks or respond to user requests.

Now, let’s understand how the Grails URL convention works based on this controller and action:

  1. Controller Name in URL:

    • The controller name, in this case, "GreetingController," is used in the URL. However, the convention capitalizes the first letter of the controller name and removes the "Controller" suffix. So, "GreetingController" becomes "greeting" in the URL.

  2. Action Name in URL:

    • By default, if you don’t specify an action in the URL, Grails assumes the "index" action. So, in this example, accessing the URL /greeting

See the end of the controllers and actions section of the user guide to find out more on default actions.

Optional: Set a Context Path

If you want to set a context path for your application, create a configuration property in the "grails-app/conf/application.yml" file:

server:
    servlet:
        context-path: /myapp

With this configuration, the application will be available at:

Alternatively, you can set the context path from the command line when using Gradle to run a Grails application. Here’s how you can do it:

$ ./gradlew bootRun -Dgrails.server.servlet.context-path=/your-context-path

Replace /your-context-path with the desired context path for your Grails application. This command sets the context path directly via the -Dgrails.server.servlet.context-path system property.

For example, if you want your application to be available at "http://localhost:8080/myapp," you can use the following command:

$ ./gradlew bootRun -Dgrails.server.servlet.context-path=/myapp

This allows you to configure the context path without modifying the application’s configuration files, making it a flexible and convenient option when running your Grails application with Gradle.

Optional: Change Server Port

If port 8080 is already in use, you can start the server on a different port using the grails.server.port system-property:

$ ./gradlew bootRun -Dgrails.server.port=9090

Replace "9090" with your preferred port.

Note for Windows Users

If you encounter an error related to the Java process or filename length, you can use the --stacktrace flag or add grails { pathingJar = true } to your "build.gradle" file.

It may also be necessary to enclose the system properties in quotes on Windows:

./gradlew bootRun "-Dgrails.server.port=9090"

Conclusion

Your Grails application will now display a "Hello, Congratulations on your first Grails application!" message when you access it in your web browser.

Remember, you can create multiple controllers and actions to build more complex web applications with Grails. Each action corresponds to a different page accessible through unique URLs based on the controller and action names.

2.5 Using Interactive Mode

The Grails Command-line Interface (CLI) offers an interactive mode, which you can access by entering "grails" in your Terminal application or Linux Command Line.

Once you’re in the command-line interface, you can enhance your efficiency by utilizing the TAB key for auto-completion. For instance:

grails> create
create-app            create-plugin         create-webapp
create-controller     create-restapi
create-domain-class   create-web-plugin

This interactive mode provides a convenient way to explore available Grails commands and options, making your Grails development workflow more efficient and user-friendly.

For more information on the capabilities of interactive mode, refer to the section on Interactive Mode in the user guide.

2.6 Getting Set Up in an IDE

Because Grails is built upon the Spring Framework (Spring Boot), the Gradle build tool, and the Groovy programming language, it is possible to develop Grails application using most popular JVM Integrated Development Environments (IDEs). Some IDEs offer more specialized support for Grails, while others may offer basic support for managing dependencies/plugins, running Gradle tasks, code-completion and syntax highlighting.

1. IntelliJ IDEA

IntelliJ IDEA is a widely used IDE for Grails development. It offers comprehensive support for Groovy and Grails, including features like code-completion, intelligent code analysis, and seamless integration with Grails artefacts.

IntelliJ IDEA also provides powerful database tools that work with Grails' GORM (Grails Object Relational Mapping) seamlessly. It offers both a Community (free) and Ultimate (paid) edition, with the latter offering more advanced Grails support, including an embedded version of the Grails Forge, and view resolution for both GSPs and JSON views.

2. Visual Studio Code (VS Code)

Visual Studio Code is a lightweight, open-source code editor developed by Microsoft. While it’s not a full-fledged IDE, it offers powerful extensions for Grails and Groovy development. You can install extensions like code-groovy and Grails for VS Code to enhance your Grails developer experience.

VS Code provides features such as syntax highlighting, code navigation, and integrated terminal support. It’s a great choice for developers who prefer a lightweight and customizable development environment.

3. STS (Spring Tool Suite)

The Spring Tool Suite (STS) is set of IDE tools designed for Spring Framework development, with versions based on both VS Code and Eclipse. This section focuses on the Eclipse version.

STS can work as an effective Grails developer platform when used with the Groovy Development Tools plugin (which can be installed using the Eclipse Marketplace). STS does not offer specific support for Grails artefacts or GSP views.

4. Netbeans

Apache Netbeans does not offer specific support for Grails, but it will import Grails applications as Gradle projects and provides reasonable editing support for Groovy and GSP views.

5. TextMate, VIM, and More

There are several excellent text editors that work nicely with Groovy and Grails. Here are some references:

  • A bundle is available for Groovy / Grails support in Textmate.

  • A plugin can be installed via Sublime Package Control for the Sublime Text Editor.

  • The emacs-grails extension offers basic support for Grails development in Emacs.

  • See this post for some helpful tips on how to set up VIM as your Grails editor of choice.

These text editors, along with the provided extensions and configurations, can enhance your Groovy and Grails development experience, offering flexibility and customization to meet your coding preferences.

2.7 Grails Directory Structure and Convention over Configuration

Grails adopts the "convention over configuration" approach to configure itself. In this approach, the name and location of files are used instead of explicit configuration. Therefore, it’s essential to become familiar with the directory structure provided by Grails. Here’s a breakdown of the key directories and links to relevant sections:

  1. grails-app - Top-Level Directory for Groovy Sources

  2. src/main/groovy - Supporting Sources

  3. src/test/groovy - Unit Tests

  4. src/integration-test/groovy - Integration Tests - For testing Grails applications at the integration level.

Understanding this directory structure and its conventions is fundamental to efficient Grails development.

2.8 Running and Debugging an Application

Grails applications can be executed using the built-in application server using the bootRun command. By default, it launches a server on port 8080:

$ ./gradlew bootRun

To specify a different port, you can set the system property -Dgrails.server.port as follows:

$ ./gradlew bootRun -Dgrails.server.port=8081

For debugging a Grails app, you have two options. You can either right-click on the Application.groovy class in your IDE and select the appropriate debugging action, or you can run the app with the following command and then connect a remote debugger to it:

$ ./gradlew bootRun --debug-jvm

For more information on the bootRun command, please refer to the bootRun section of the Grails reference guide.

2.9 Testing an Application

Grails offers a convenient feature where you can automatically generate unit and integration tests for your application using the create-* commands. These generated tests are stored in the src/test/groovy and src/integration-test/groovy directories. However, it is your responsibility to populate these tests with the appropriate test logic. You can find comprehensive guidance on crafting valid test logic in the section dedicated to Unit and Integration Tests.

To initiate the execution of your tests, including both unit and integration tests, you can utilize the Gradle check task. Follow these steps:

  1. Open your terminal or command prompt and navigate to your Grails project’s root directory.

  2. Execute the following Gradle command:

    $ ./gradlew check

    By running the check task, you ensure that all tests in your Grails project, including the ones you’ve created and populated with test logic, are executed. This comprehensive testing approach contributes significantly to the robustness and overall quality of your application.

  3. Viewing Test Reports: After running your tests, Grails generates test reports that provide valuable insights into the test results. You can typically find these reports in the build/reports/tests directory of your Grails project. Open these reports in a web browser to view detailed information about test outcomes, including passed, failed, and skipped tests.

Remember, testing is not just a process; it’s a fundamental practice that enhances your Grails application’s reliability. Viewing test reports helps you analyze and understand the test results, making it easier to identify and address any issues.

By following these testing practices and reviewing test reports, you can deliver a high-quality Grails application to your users with confidence.

2.10 Deploying an Application

Grails applications offer multiple deployment options.

For traditional container deployments, such as Tomcat or Jetty, you can generate a Web Application Archive (WAR) file using the Gradle war task as follows:

$ ./gradlew war

This task generates a WAR file with a -plain suffix within the build/libs directory, ready for deployment according to your container’s guidelines.

By default, the war task runs in the production environment. You can specify a different environment, such as development, by overriding it in the Gradle command:

$ ./gradlew -Dgrails.env=dev war

If you prefer not to use a separate Servlet container, you can create and run the Grails WAR file as a regular Java application:

$ ./gradlew bootWar
$ java -jar build/libs/mywar-0.1.war

When deploying Grails, ensure that your container’s JVM runs with the -server option and sufficient memory allocation. Here are recommended VM flags:

-server -Xmx1024M

2.11 Supported Java EE Containers

The Grails framework requires that runtime containers support Servlet 3.0 and above. By default, Grails framework applications are bundled with an embedded Tomcat server. For more information, please see the Deployment section of this documentation.

In addition, read the Grails Guides for tips on how to deploy Grails to various popular Cloud services.

2.12 Creating Artefacts

Grails provides a set of useful CLI commands for various tasks, including the creation of essential artifacts such as controllers and domain classes. These commands simplify the development process, although you can achieve similar results using your preferred Integrated Development Environment (IDE) or text editor.

For instance, to create the foundation of an application, you typically need to generate a domain model using Grails Commands:

$ grails create-app myapp
$ cd myapp
$ grails create-domain-class book

Executing these commands will result in the creation of a domain class located at grails-app/domain/myapp/Book.groovy, as shown in the following code:

package myapp

class Book {
}

The Grails CLI offers numerous other commands that you can explore in the Grails command line reference guide.

Using interactive mode enhances the development experience by providing auto-complete and making the process smoother.

2.13 Generating an Application

Quick Start with Grails Scaffolding

To quickly initiate your Grails project, you can employ the runCommand Gradle task. This task allows you to generate the essential structure of an application swiftly. Specifically, when running the following command, you can create a controller (including its unit tests) and the associated views for your application:

$ ./gradlew runCommand -Pargs="generate-all myapp.Book"