Chapter 6. Applying Grails in Spring Boot

This chapter covers

  • Persisting data with GORM
  • Defining GSP views
  • An introduction to Grails 3 and Spring Boot

When I was growing up, there was a series of television advertisements involving two people, one enjoying a chocolate bar and another eating peanut butter out of a jar. By way of some sort of comedic mishap, the two would collide, resulting in the peanut butter and chocolate getting mixed.

One would proclaim, “You got your chocolate in my peanut butter!” The other would respond, “You got peanut butter on my chocolate!”

After initially being angry with their circumstances, the two would conclude that the combination of peanut butter and chocolate is a good thing. Then a voice-over would suggest that the viewer should eat a Reese’s Peanut Butter Cup.

From the moment that Spring Boot was announced, I’ve been frequently asked how to choose between Spring Boot and Grails. Both are built upon the Spring Framework and both help ease application development. Indeed, they’re very much like peanut butter and chocolate. Both are great, but the choice is largely a personal one.

As it turns out, there’s no reason to choose one or the other. Just like the chocolate vs. peanut butter debate, Spring Boot and Grails are two great choices that work great together.

In this chapter, we’re going to look at the connection between Grails and Spring Boot. We’ll start by looking at a few Grails features like GORM and Groovy Server Pages (GSP) that are available in Spring Boot. Then we’ll flip it around and see how Grails 3 has been reinvented by being built upon Spring Boot.

6.1. Using GORM for data persistence

Probably one of the most intriguing pieces of Grails is GORM (Grails object-relational mapping). GORM makes database work as simple as declaring the entities that will be persisted. For example, listing 6.1 shows how the Book entity from the reading-list example could be written in Groovy as a GORM entity.

Listing 6.1. A GORM Book entity

Just like its Java equivalent, this Book class has a handful of properties that describe a book. Unlike the Java version, however, it’s not littered with semicolons, public or private modifiers, setter and getter methods, or any of the other noise that’s common in Java. But what makes it a GORM entity is that it’s annotated with the @Entity annotation from Grails. This simple entity does a lot, including mapping the object to the database and enabling Book with persistence methods through which it can be saved and retrieved.

To use GORM with a Spring Boot project, all you must do is add the GORM dependency to your build. In Maven, the <dependency> looks like this:

<dependency>
  <groupId>org.grails</groupId>
  <artifactId>gorm-hibernate4-spring-boot</artifactId>
  <version>1.1.0.RELEASE</version>
</dependency>

The same dependency can be expressed in a Gradle build like this:

compile("org.grails:gorm-hibernate4-spring-boot:1.1.0.RELEASE")

This library carries some Spring Boot auto-configuration with it that will automatically configure all of the necessary beans to support working with GORM. All you need to do is start writing the code.

Another GORM option for Spring Boot

As its name suggests, the gorm-hibernate4-spring-boot dependency enables GORM for data persistence via Hibernate. For many projects, this will be fine. If, however, you’re interested in working with the MongoDB document database, you’ll be pleased to know that GORM for MongoDB is also available for Spring Boot.

The Maven dependency looks like this:

<dependency>
  <groupId>org.grails</groupId>
  <artifactId>gorm-mongodb-spring-boot</artifactId>
  <version>1.1.0.RELEASE</version>
</dependency>

Likewise, the Gradle dependency is as follows:

compile("org.grails:gorm-mongodb-spring-boot:1.1.0.RELEASE")

Due to the nature of how GORM works, it requires that at least the entity class be written in Groovy. We’ve already written the Book entity in listing 6.1. As for the Reader entity, it’s shown in the following listing.

Listing 6.2. A GORM Reader entity

Now that we’ve written the two GORM entities for the reading-list application, we’ll need to rewrite the rest of the app to use them. Because working with Groovy is such a pleasant experience (and very Grails-like), we’ll continue writing the other classes in Groovy as well.

First up is ReadingListController, as shown next.

Listing 6.3. A Groovy reading-list controller

The most obvious difference between this version of ReadingListController and the one from chapter 3 is that it’s written in Groovy and lacks much of the code noise from Java. But the most significant difference is that it doesn’t work with an injected ReadingListRepository anymore. Instead, it works directly with the Book type for persistence.

In the readersBooks() method, it calls the static findAllByReader() method on Book to fetch all books for the given reader. Although we didn’t write a findAllByReader() method in listing 6.1, this will work because GORM will implement it for us.

Likewise, the addToReadingList() method uses the static withTransaction() and the instance save() methods, both provided by GORM, to save a Book to the database.

And all we had to do was declare a few properties and annotate Book with @Entity. A pretty good payoff, if you ask me.

A similar change must be made to SecurityConfig to fetch a Reader via GORM rather than using ReadingListRepository. The following listing shows the new Groovy SecurityConfig.

Listing 6.4. SecurityConfig in Groovy

Aside from being rewritten in Groovy, the most significant change in SecurityConfig is the second configure() method. As you can see, it uses a closure (as the implementation of UserDetailsService) that looks up a Reader by calling the static findByUsername() method, which is provided by GORM.

You may be wondering what becomes of ReadingListRepository in this GORM-enabled application. With GORM handling all of the persistence for us, ReadingListRepository is no longer needed. Neither are any of its implementations. I think you’ll agree that less code is a good thing.

As for the remaining code in the application, it should also be rewritten in Groovy to match the classes we’ve changed thus far. But none of it deals with GORM and is therefore out of scope for this chapter. The complete Groovy application is available in the example code download.

At this point, you can fire up the reading-list application using any of the ways we’ve already discussed for running Spring Boot applications. Once it starts, the application should work as it always has. Only you and I know that the persistence mechanism has been changed.

In addition to GORM, Grails apps usually use Groovy Server Pages to render model data as HTML served to the browser. The Grails-ification of our application continues in the next section, where we’ll replace the Thymeleaf templates with equivalent GSP.

6.2. Defining views with Groovy Server Pages

Up until now, we’ve been using Thymeleaf templates to define the view for the reading-list application. In addition to Thymeleaf, Spring Boot also offers Freemarker, Velocity, and Groovy-based templates. For any of those choices, all you must do is add the appropriate starter to your build and start writing templates in the templates/ directory at the root of the classpath. Auto-configuration takes care of the rest.

The Grails project also offers auto-configuration for Groovy Server Pages (GSP). If you want to use GSP in your Spring Boot application, all you must do is add the GSP for Spring Boot library to your build:

compile("org.grails:grails-gsp-spring-boot:1.0.0")

Just like the other view template options offered by Spring Boot, simply having this library in your classpath triggers auto-configuration that sets up the view resolvers necessary for GSP to work as the view layer of Spring MVC.

All that’s left is to write the GSP templates for your application. For the reading-list application, we’ll need to rewrite the Thymeleaf readingList.html file in GSP form as readingList.gsp (in src/main/resources/templates). The following listing shows the new GSP-enabled reading-list template.

Listing 6.5. The reading-list app’s main view written in GSP

As you can see, the GSP template is sprinkled with expression language references (the parts wrapped in ${}) and tags from the GSP tag library such as <g:if> and <g:each>. It’s not quite pure HTML as is the case with Thymeleaf, but it’s a familiar and comfortable option if you’re used to working with JSP.

For the most part, it’s rather straightforward to map the elements on this GSP template with the corresponding Thymeleaf templates from chapters 2 and 3. One thing to note, however, is that you have to put in a hidden field to carry the CSRF (Cross-Site Request Forgery) token. Spring Security requires this token on POST requests, and Thymeleaf is able to automatically include it in the rendered HTML. With GSP, however, you must explicitly include the CSRF token in a hidden field.

Figure 6.1 shows the results of the GSP rendered as HTML in the browser after a few books have been entered.

Figure 6.1. The reading list rendered from a GSP template

Although Grails features like GORM and GSP are appealing and go a long way toward making a Spring Boot application even simpler, it’s not quite the complete Grails experience. We’ve seen how to put a little Grails chocolate in the Spring Boot peanut butter. Now we’ll turn it around and see how Grails 3 gives you the best of both worlds: a development experience that’s both fully Spring Boot and fully Grails.

6.3. Mixing Spring Boot with Grails 3

Grails has always been a higher-level framework built upon the giants of Spring, Groovy, Hibernate, and others. With Grails 3, Grails is now built upon Spring Boot, enabling a very compelling developer experience that makes both Grails developers and Spring Boot developers feel at home.

The first step toward working with Grails 3 is to install it. On Mac OS X and most Unix systems, the easiest way to install Grails is to use SDKMAN at the command line:

$ sdk install grails

If you’re using Windows or otherwise can’t use SDKMAN, you’ll need to download the binary distribution, unzip it, and add the bin directory to your system path.

Whichever installation choice you use, you can verify the installation by checking the Grails version at the command line:

$ grails -version

Assuming the installation went well, you’re now ready to start creating a Grails project.

6.3.1. Creating a new Grails project

The grails command-line tool is what you’ll use to perform many tasks with a Grails project, including the initial creation of the project. To kick off the reading-list application project, use grails like this:

$ grails create-app readinglist

As its name suggests, the create-app command creates a new application project. In this case, the name of the project is “readinglist”.

Once the grails tool has created the application, cd into the readinglist directory and take a look at what was created. Figure 6.2 shows a high-level view of what the project structure should look like.

Figure 6.2. The directory structure of a Grails 3 project

You should recognize a few familiar entries in the project’s directory structure. There’s a Gradle build specification and configuration (build.gradle and gradle.properties). There’s also a standard Gradle project structure under the src directory. But grails-app is the most interesting directory in the project. If you’ve ever worked with any previous version of Grails, you’ll know what this directory is for. It’s where you’ll write the controllers, domain types, and other code that makes up the Grails project.

If you dig a little deeper and open up the build.gradle file, you’ll find a few more familiar items. To start with, the build specification uses the Spring Boot plugin for Gradle:

apply plugin: "spring-boot"

This means that you’ll be able to build and run the Grails application just as you would any other Spring Boot application.

You’ll also notice that there are a handful of Spring Boot libraries among the other 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"
  ...
}

This provides your Grails application with Spring Boot auto-configuration and logging, as well as the Actuator and an embedded Tomcat to serve the application when run as an executable JAR.

Indeed, this is a Spring Boot project. It’s also a Grails project. As of Grails 3, Grails is built upon a foundation of Spring Boot.

Running the application

The most straightforward way to run a Grails application is with the run-app command of the grails tool at the command line:

$ grails run-app

Even though we’ve not written a single line of code, we’re already able to run the application and view it in the browser. Once the application starts up, you can navigate to http://localhost:8080 in your web browser. You should see something similar to what’s shown in figure 6.3.

Figure 6.3. Running a freshly created Grails application

The run-app command is the Grails way of running the application and has been the way to run Grails applications for years, even in previous versions of Grails. But because this Grails 3 project’s Gradle specification uses the Spring Boot plugin for Gradle, you can also run the application using any of the means available to a Spring Boot project. This includes the bootRun task via Gradle:

$ gradle bootRun

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

$ gradle build
...
$ java -jar build/lib/readingList-0.1.jar

Of course, the WAR file produced by the build can also be deployed to a servlet 3.0 container of your choice.

It’s very convenient to be able to run the application this early in the development process. It helps you know that the project has been properly initialized. But the application doesn’t do much interesting yet. It’s up to us to build upon the initial project. We’ll start by defining the domain.

6.3.2. Defining the domain

The central domain type in the reading-list application is the Book class. Although we could manually create a Book.groovy file, it’s usually better to use the grails tool to create domain types. That’s because it knows where the source files go and it’s also able to generate any related artifacts for us at the same time.

To create the Book class, we’ll use the create-domain-class command of the grails tool:

$ grails create-domain-class Book

This will generate two source files: a Book.groovy file and a BookSpec.groovy file. The latter is a Spock specification for testing the Book class. It’s initially empty, but you can fill it with any tests you need to verify the functionality of a Book.

The Book.groovy file defines the Book class itself. You’ll find it in grails-app/domain/readingList. Initially, it’s rather empty and looks like this:

package readinglist
class Book {

  static constraints = {
  }
}

We’ll need to add the fields that define a book, such as the title, author, and ISBN. After adding the fields, Book.groovy looks like this:

package readinglist
class Book {

  static constraints = {
  }

  String reader
  String isbn
  String title
  String author
  String description

}

The static constraints variable is where you can define any validation constraints to be enforced on instances of Book. In this chapter, we’re primarily interested in building out the reading-list application to see how it’s built upon Spring Boot and not so much on validation. Therefore, we’ll leave the constraints empty. Feel free to add constraints if you wish, though. Have a look at Grails in Action, Second Edition, by Glen Smith and Peter Ledbrook (Manning, 2014) for more information.[1]

1

Although Grails in Action, Second Edition, covers Grails 2, much of what you learn about Grails 2 applies to Grails 3.

For the purpose of working with Grails, we’re going to keep the reading-list application simple and in line with what we wrote in chapter 2. Therefore, we’ll forego creating a Reader domain and go ahead and create the controller.

6.3.3. Writing a Grails controller

As with domain types, it’s easy to create controllers using the grails tool. In the case of controllers, you have a few choices of commands, however:

  • create-controller—Creates an empty controller, leaving it to the developer to write the controller’s functionality
  • generate-controller—Generates a controller with scaffolded CRUD operations for a given domain type
  • generate-all—Generates a scaffolded CRUD controller and associated views for a given domain type

Although scaffolded controllers are very handy and are certainly one of the most well-known features of Grails, we’re going to keep it simple and write a controller that has just enough functionality to mimic the behavior of the application we created in chapter 2. Therefore, we’ll use the create-controller command to create a bare-bones controller and then fill it in with the methods we need:

$ grails create-controller ReadingList

This command creates a controller named ReadingListController in grails-app/controllers/readingList that looks like this:

package readinglist
class ReadingListController {

  def index() { }
}

Without making any changes, this controller is ready to run, although it won’t do much. At this point, it will handle requests whose path is /readingList and forward the request to the view defined at grails-app/views/readingList/index.gsp (which doesn’t yet exist, but we’ll create soon).

But what we need our controller to do is display a list of books and a form to add a new book. We also need it to handle the form submission and save a book to the database. The following listing shows the ReadingListController that we need.

Listing 6.6. Fleshing out the ReadingListController

Although it’s much shorter than the equivalent Java controller, this version of ReadingListController is almost completely functionally equivalent. It handles GET requests for /readingList and fetches a list of books to be displayed. And when the form is submitted, it handles the POST request, saves the book, then redirects to the index action (which is handled by the index() method).

Incredibly, we’re almost finished with the Grails version of the reading-list application. The only thing left is to create the view that displays the list of books and the form.

6.3.4. Creating the view

Grails applications typically use GSP templates for their views. You’ve already seen how to use GSP in a Spring Boot application, so the template we need won’t be much different from the one in section 6.2.

What we might want to do, however, is take advantage of the layout facilities offered in Grails to apply a common design to all of the pages in the application. As you can see in listing 6.7, it’s a rather straightforward and simple change.

Listing 6.7. A Grails-ready GSP template, including layout

Within the <head> element we’ve removed the <link> tag that references our stylesheet. In its place, we’ve put in a <meta> tag that references the “main” layout of the Grails application. As a consequence, the application will take on the Grails look and feel, as shown in figure 6.4, when you run it.

Figure 6.4. The reading-list application with the common Grails styling

Although the Grails style is more eye-catching than the simple stylesheet we’ve been using, there is obviously still a little work to do to make the reading-list application look good. And we’ll probably want to start making the application look a little less like Grails and more like what we want our application to look like. Manipulating the application’s stylesheets is well outside of the scope of this book, but if you’re interested in tweaking the look and feel, you’ll find the stylesheets in the grails-app/assets/stylesheets directory.

6.4. Summary

Both Grails and Spring Boot aim to make developers’ lives easy, providing a greatly simplified development model on top of Spring, so it may appear that these are competing frameworks. But in this chapter, we’ve seen how to get the best of both worlds by bringing Spring Boot and Grails together.

We looked at how to add GORM and GSP views, two well-known Grails features, to an otherwise typical Spring Boot application. GORM is an especially welcome feature in Spring Boot, enabling you to perform persistence directly with the domain and eliminating the need for a repository.

Then we looked at Grails 3, the latest incarnation of Grails, built upon Spring Boot. When developing a Grails 3 application, you’re also working with Spring Boot and are afforded all of the features of Spring Boot, including auto-configuration.

In all cases, both in this and the previous chapter, you’ve seen how mixing Groovy and Spring Boot helps squelch the code noise that’s required in the Java language.

Coming up in the next chapter, we’re going to shift our attention away from coding Spring Boot applications and look at the Spring Boot Actuator to see how it gives us insights into the inner workings of our running applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset