Grails has always been a high-level framework built on the shoulders of Spring, Groovy, Hibernate and other giants. By Grails 3, Grails has been built on Spring Boot, providing an enjoyable development experience. Both Grails developers and Spring Boot developers are at home.

To use Grails 3, you need to install it first. On Mac OS X and most Unix systems, the easiest way to install it is to use SDKMAN on the command line:

$ sdk install grails

If you’re running Windows or don’t have access to SDKMAN, you’ll need to download the binary distribution. After decompressing, add the bin directory to the system path.

Either way, you can verify the installation by viewing the version of Grails on the command line:

$ grails -version

If the installation is successful, you are now ready to create your Grails project.

Create a new Grails project

In Grails projects, you’ll use the Grails command line tools to perform many tasks, including creating projects. To create a reading list project, use the Grails command like this:

$ grails create-app readinglist

As the name of the command indicates, create-app creates a new application project. The project in this example is called ReadingList.

Once the Grails tools have created the application and the CD is in the ReadingList directory, take a look at what you’ve created. The diagram below should give you an overview of the project structure.

In this project directory structure, you should recognize something familiar. Here is a Gradle build specification file and configuration (build. Gradle and gradle.properties). The SRC directory also has a standard Gradle project structure, but grails-app is probably the most interesting directory in it. If you’ve used older versions of Grails, you know what this directory does. This is where you put your controllers, domain classes, and other code that makes up your Grails project.

If you dig a little deeper and open the build.gradle file, you’ll find something more familiar. First, the build instructions file uses the Gradle plugin for Spring Boot:

apply plugin: "spring-boot"

This means you can build and run this Grails application just like any other Spring Boot application.

You should also note that there are quite a few useful Spring Boot libraries in the dependencies:

dependencies { 
 compile 'org.springframework.boot:spring-boot-starter-logging' 
 compile("org.springframework.boot:spring-boot-starter-actuator") 
 compile "org.springframework.boot:spring-boot-autoconfigure" 
 compile "org.springframework.boot:spring-boot-starter-tomcat". }Copy the code

These libraries provide automatic configuration for Spring Boot, logging, and Actuator and embedded Tomcat for Grails applications. This Tomcat provides services when the application is run as an executable JAR.

In fact, this is a Spring Boot project, as well as a Grails project, because Grails 3 is built on Spring Boot.

Run the application

The most direct way to run a Grails application is to use the Run-app command of the Grails tool from the command line:

$ grails run-app
Copy the code

Even if we haven’t written a single line of code yet, we can run the application and access it in the browser. Once the application starts, you can access http://localhost:8080 in your browser. You should see a page similar to the one below.

Running applications in Grails using the run-app command has been around for years, as was the case with the last version of Grails. Grails 3 uses the Gradle plugin for Spring Boot in the Gradle instructions. You can also run the application in a variety of ways. Here the bootRun task is introduced via Gradle:

$ gradle bootRun

You can also build the project and run the generated executable JAR file:

$ gradle build 
... 
$ java -jar build/lib/readingList-0.1.jar
Copy the code

Of course, the WAR files generated by the build can be deployed to any Servlet 3.0 container you like.

It is convenient to be able to run your application early in development and help you verify that your application has been properly initialized. But the application hasn’t done anything interesting yet, and what it does on the initialized project is entirely up to us. Next, start defining the domain model.

Define the domain model

The core domain model in the reading list application is the Book class. Although you can create book.groovy files by hand, it’s usually better to use the Grails tools to create domain model classes. Because it knows where to put files and can generate all kinds of related content at the same time.

To create the Book class, we use the create-domain-class command of the Grails tools:

The $grails create-domain-class Book command generates two source files: book. groovy and bookspec. groovy. The latter is a Spock specification that tests the Book class. At first this file is empty, and you can fill it with various tests to verify the various features of Book.

The Book class is defined in the book. groovy file, which you can find in grails-app/domain/readingList. It starts out with basically nothing:

package readinglist 
class Book { 
 static constraints = { 
 } 
}
Copy the code

We need to add fields to define a book, such as title, author, and ISBN. After you add these fields, book.groovy looks like this:

package readinglist 
class Book { 
 static constraints = { 
 }
 String reader 
 String isbn 
 String title 
 String author 
 String description 
}
Copy the code

Static Constraints variables allow you to define various validation constraints that can be attached to the Book instance. In this chapter, we’ll focus on building a reading list application, looking at how to build an application based on Spring Boot without focusing too much on validation. Therefore, the constraints content is empty. Of course, feel free to add constraints if you need to. Check out Grails in Action, Second Edition by Glen Smith and Peter Ledbrook.

To use Grails, we want to keep our reading list application clean and consistent with what we’ve written before. So, we’re going to create the Reader domain model, and the controller.

Develop the Grails controller

With the domain model, it’s easy to create controllers through grails tools. There are several commands to choose from regarding the controller.

  • create-controller: Create an empty controller and let the developer write the controller’s functionality.
  • generate-controller: Generates a controller that contains basic CRUD operations for domain-specific model classes.
  • generate-all: Generates basic CRUD controllers for domain-specific model classes, and their views.

Scaffolding controllers are nice to use and one of the better known features of Grails, but we’ll keep it simple and write a controller with only the necessary functionality that matches the functionality of the previously written application. Therefore, we use the create-controller command to create the original controller and then fill in the required methods.

$ grails create-controller ReadingList

This command will in grails – app/controllers/readingList create a controller called ReadingListController:

package readinglist 
class ReadingListController { 
 def index(a) {}}Copy the code

You don’t have to change a single line of code, and the controller runs, even though it doesn’t do anything. At this point, it can deal with to/readingList request, the request to grails – app/views/readingList/index. The GSP in view of the definition of (not yet, now we will create later).

We need the controller to display the list of books, as well as a form to add new books. We also need the ability to submit forms and save new books to the database. The following code is the ReadingListController we need.

package readinglist 
import static org.springframework.http.HttpStatus.* 
import grails.transaction.Transactional 
class ReadingListController { 
 def index(a) { 
 respond Book.list(params), model:[book: new Book()] 
 } 
 @Transactional 
 def save(Book book) { 
 book.reader = 'Craig' 
 book.save flush:true
 redirect(action: "index")}}Copy the code

Although the code length is considerably shorter than the equivalent Java controller, this version of ReadingListController is almost complete. It handles GET requests to /readingList to retrieve and display a list of books. After the form is submitted, it also handles the POST request, saves the book, and then redirects back to the Index action (handled by the index() method).

Amazingly, we’re almost done with the Grails version of our reading list application. All that is left is to create a view that displays the book list and form.

Create a view

Grails applications typically use GSP templates for their views.

What we want to do is take advantage of the layout facilities that Grails provides to apply a common design style to the entire application.

<! DOCTYPEhtml> 
<html> 
 <head> 
 <meta name="layout" content="main"/>
 <title>Reading List</title> 
 <link rel="stylesheet" 
 href="/assets/main.css? compile=false" /> 
 <link rel="stylesheet" 
 href="/assets/mobile.css? compile=false" /> 
 <link rel="stylesheet" 
 href="/assets/application.css? compile=false" /> 
 </head> 
<body>
 <h2>Your Reading List</h2> 
 <g:if test="${bookList && ! bookList.isEmpty()}"> 
 <g:each in="${bookList}" var="book"> 
 <dl> 
 <dt class="bookHeadline"> 
 ${book.title}</span> by ${book.author} 
 (ISBN: ${book.isbn}") 
 </dt> 
 <dd class="bookDescription"> 
 <g:if test="${book.description}"> 
 ${book.description} 
 </g:if> 
 <g:else> 
 No description available 
 </g:else> 
 </dd> 
 </dl> 
 </g:each> 
 </g:if> 
 <g:else> 
 <p>You have no books in your book list</p> 
 </g:else> 
 <hr/> 
 <h3>Add a book</h3> 
 <g:form action="save">
 <fieldset class="form"> 
 <label for="title">Title:</label> 
 <g:field type="text" name="title" value="${book? .title}"/><br/> 
 <label for="author">Author:</label> 
 <g:field type="text" name="author" 
 value="${book? .author}"/><br/> 
 <label for="isbn">ISBN:</label> 
 <g:field type="text" name="isbn" value="${book? .isbn}"/><br/> 
 <label for="description">Description:</label><br/> 
 <g:textArea name="description" value="${book? .description}" 
 rows="5" cols="80"/> 
 </fieldset> 
 <fieldset class="buttons"> 
 <g:submitButton name="create" class="save" 
 value="${message(code: 'default.button.create.label', default: 'Create')}" /> 
 </fieldset> 
 </g:form> 
 </body> 
</html>
Copy the code

Remove the tag referencing the stylesheet from the element. Here you put a
tag that introduces the Main layout of your Grails application. This way, your application can use the look and feel of Grails, as shown below.

Although the Grails style is more eye-catching than the simple stylesheets used before. But it’s clear that there’s still some work to be done to make the reading list application look better. The first step is to make your application a little less grails-like and a little more like what we imagine. Modifying an application’s stylesheets is outside the scope of this book, but if you’re interested in style tweaking, you can find stylesheets files in the Grails-app /assets/stylesheets directory.