Going Live with a Grails-Powered Blog

he DevX article Build Your First Grails Project: A Grails-Powered Blog showed how easy it is to create a purely functional web application using Grails. This article expands on the original source code from Build Your First Grails Project to get the blog application ready to go live. The process requires the following steps:

  1. Creating an RSS feed with Groovy Builders
  2. Securing the blog
  3. Using layouts for presentation
  4. Testing the application
  5. Tagging posts using AJAX
  6. Deploying the project as a war file

Getting Out There with RSS
The blog from Build Your First Grails Project allows users to create posts and leave comments on posts. Now it needs an RSS feed to tell people about updates to the blog. Groovy provides an extremely simple mechanism called builders for constructing node-based structures, such as XML. A Groovy builder is a class that intercepts closure calls on it and builds up a node tree internally that represents the calls that have been made on it.

For comparison, consider the options for constructing an RSS feed in Java:

  • Build up an XML-formatted string.
  • Use the XML DOM to construct the XML
  • Download an open source RSS library such as Rome.

The first option is error prone, as there is no inherent structure in the contents of a string. The second option is extremely verbose and memory intensive. All the elements need to be constructed as objects, have their content and attributes set, and finally have all their children connected. The third option (using an external library) works and it avoids the problems of the other two, but it adds another dependency to the project. Enter Groovy builders.

The code in Listing 1 enables you to implement an RSS feed with Groovy Builders. It uses the Grails support for rendering with the Groovy MarkupBuilder to construct an RSS feed from the existing blog posts.

Listing 1 created an action in the PostController called rss. The posts are loaded in descending date order and then the RSS feed is rendered by calling the render method and specifying the content type as XML and passing in a builder closure that constructs the XML response.

The problem with this approach is you are not able to add a link element, as controllers automatically have a link method made available for creating HTML links. To get round this, you need to use the Groovy MarkupBuilder directly from a separate class. This class must be created in the src directory at the same level as the grails-app directory (see Listing 2 for an example).

You then need to modify the render method in the rss action to be like this, which also makes the action much more concise:

render(contentType: "text/xml,"        text:new PostRssBuilder(request:request)                .buildRss(posts))

When using the Groovy MarkupBuilder each of the closure definitions represent an XML element, while the arguments to the closure either define the content of the element (if the argument is a String) or the attributes of the element (if the argument is a Map). Listing 3 shows the XML that will be generated by the MarkupBuilder for this example.

The XML generated by the builder will create a root node called “rss” with the attribute version=”2.0.” The “rss” element will have a single child “channel” and the “channel” element will have a single title, link, description, and language element with an item element for each post. The Groovy each method is used to generate an item element for each post.

Securing The Blog
You need to add some authentication to the blog so only you can make and edit posts. You will use a filter to secure certain actions and a tag to hide features that should be available only to authenticated users. On a larger project, integrating with a security framework like Acegi Security would be more appropriate for authentication, but this approach allows you to see how trivial implementing filters and tags are in Grails.

The filter code is a Groovy class that must exist in the grails-appconf directory. Grails will pick up all classes that end in “Filters” in the conf directory as containing filter definitions. The filter class must have a closure defined called “filters.” Each node within this closure defines a filter.

You can see from the UserFilters class in the following listing that an “authenticated” filter has been declared:

class UserFilters {  def filters = {    authenticated(controller: "post", action: "edit") {      before = {        if (!session.user) {          redirect(controller: "user", action: "login")          return false        }      }    }  }}

The arguments that are passed to the filter determine the scope of the filter (i.e., which actions and controllers the filter is executed for). In the application, you have only one action that needs to be secured: the edit post action. You can declare the scope of the filter by controller and action, or by URI. To force a user to log in when adding a comment to a post, you would define all actions on the comment controller as being secure:

authenticated(controller: "comment," action: "*") {...}

Alternatively, you could control this access via the URI:

authenticated(uri: "/comment/**") {...}

The closure definition in the UserFilters class tells Grails to execute the filter before the action is performed. You could also have defined the filter to execute after the action is performed or “afterView,” which would execute the filter when the view had been rendered.

A simple check determines whether there is a user attribute in the session. If not, the user is redirected to the login page. Returning false in the filter informs Grails that the requested action should not be executed.

At this point, a Java web developer who isn’t familiar with Grails might have a few questions:

  1. Where did the session come from?
  2. Since when has there been a user property on the HTTPServletSession interface?
  3. Should a user property really return true?

These are all valid concerns with simple answers:

  1. Grails exposes a number of objects to the filter for convenience, including the session object.
  2. Grails also dynamically adds some convenience conventions to the HTTPServletSession interface to allow session attributes to be accessed as if they were properties on the session object.
  3. A Boolean comparison in Groovy doesn’t just check if something is true or false, but also if it is null, zero, or some other form of false (depending on the object being compared). In this instance, if the user is not in the session then the property will return null and equal false for the if statement.

Testing the Security
Create a new controller called UserController with this code under the grails-appviewsuser directory:

class UserController {  def login = {    render(view: "login")  }}

The UserController will render the login page when authentication is required. In the same grails-appviewsuser directory, create a new login.gsp with this code:

<%@ page contentType="text/html;charset=UTF-8" %>Login  

The login page will ask the user to enter his or her username and password. You are now ready to run the application (grails run-app) and test whether the edit post action is secure.

When the application is running, if you go to the post list page (http://localhost:8080/groovypublish/post) and then try to click on the “Create a new post” or “Edit this post” links, you will be taken to the login page (see Figure 1).

Figure 1. Login Required: A login page is displayed if a user tries to create a new post or edit a post.

Now Let Me In!
Now that you have secured the application, you need to be able to authenticate a valid user so you can get in and write posts.

The first thing you need is a User domain object to store the authentication details of a blog user (see Listing 4). This class is created in the domain directory along with the other domain objects. The only new feature here is the addition of the unique constraint on the username field. This checks if the username is unique in the database when validation is performed.

The next task is to update the UserController to have an authenticate action. There are two interesting aspects to this code: the introduction of the UserService and the use of the flash scope through the flash property.

In Grails, a service is convention in the same way that domain objects and controllers are conventions. If a UserService Groovy class exists in the grails-appservices directory, then it becomes a Grails service. Services contain business logic that can be reused by other classes. By defining a property in the controller with the same name as the service class, Grails uses Spring to automatically inject an instance of the service into the controller (more on the implementation of the service later).

Grails also introduces a new scope to Java web development. To the currently available request scope and session scope, Grails adds something called flash scope (an idea taken from the Ruby on Rails framework). The lifespan of flash scope begins while one user request is being serviced and ends when the following user request has finished executing. It is commonly used (as in this blog example) to pass data to a request that will be performed as a redirect without having to add the data to the query string of the redirect. In the authenticate action example in the previous section, for example, if the authentication fails:

  1. A message will be put in flash scope.
  2. A redirect will be sent back to the client’s browser.
  3. The message will be available in flash scope to be rendered when the login page is requested.

The final step is to perform the authentication, which the authenticate method on the user service does by returning the result of a search for users with the given username and password. The interesting thing here is the use of the Grails Object Relational Mapping (GORM) dynamic finders. Internally, Grails builds up a Hibernate query based on the properties that are specified in the name of the find method. To further illustrate this, the eventual SQL that would be executed by this dynamic finder may look something like this:

select * from user where username = ? and password = ?

It is also possible to add suffixes to the properties that perform comparison operations other than equals:

def post = Post.findByTitleLike("%grails%")def comment = Comment.findByDateCreatedGreaterThan(yesterday)

See the online Grails documentation for a full set of the comparison suffixes that can be used for dynamic finders.

The final step before you can log in is to create a user in the BootStrap class:

new User(username:"me",        password:"password",        firstName:"A",        lastName:"Developer").save()                 

Now if you go back to the application you should be able to log in with username “me” and the password “password.” There is also a logout action on the controller in UserController, so you can put a link like the following on the post list page to logout from the application:


You will see how to make the logout link available on all pages later.

You Can’t Do That
To finish off this basic security mechanism, you need to be able to hide the links that require authentication from unauthenticated users. You could do this by wrapping each link with an “if” statement or a tag that checks the session, or you can write your own tag that will handle this automatically.

The convention for tag libraries is that they must exist in a class that ends with TagLib and exists in the grails-app aglib directory. The static namespace property determines the namespace that will be used to access the tags from a GSP, from other tags, or from controllers. To define a tag, you create a closure that takes a map of attributes and the body of the tag:

public class SecureTagLib {  static namespace = "gp"  def secureLink = { attrs, body ->    if(session.user) {      out << g.link(attrs, body)    }  }}
Figure 2. An Unauthenticated User View: Users that have not been authenticated should not see the links to create a new post and edit a post.

The secure link tag checks if a user is in the session and, if so, passes on its arguments to the Grails link tag that you would normally use. The link tag can either be called directly or through the g namespace property. (The g namespace property is used for clarity in case another link tag is created in a separate namespace in the future.)

Everything in Groovy is an object, even operators. This allows operators to be overridden. The << (left shift) operator has been overridden in Groovy to mean "append to" for objects such as StringBuffers, Writers, Lists, Files, and Sockets. This tag can now be used in a GroovyServer Page (GSP) to hide links that should not be accessible to unauthenticated users (see Figure 2).

To allow authenticated users to be able to create and edit posts (see Figure 3), replace this code:

  Create a new post
Figure 3. An Authenticated User View: Authenticated users should be able to create and edit posts.

With this code:

  Create a new post

And this code:

  Edit this post

With this code:

  Edit this post

Making Yourself Presentable
The next step in getting the application ready for launch is to think about making it more presentable?not that you would leave user interface considerations to this late stage on a normal project! So far the HTML is clean and minimal, but you need to think about common page elements and styling.

Grails uses SiteMesh as its rendering technology. The SiteMesh layouts are defined in the grails-app/views/layouts directory. You can apply the default Grails layout to the post/list.gsp file by using an HTML meta tag like this:

This tells SiteMesh that main.gsp should be used as the layout for this page. Figure 4 shows the result of applying the default Grails layout.

Figure 4. Applying the Default Grails Layout: You can apply the default layout template that comes with Grails to the application.

To create your own layout, create the file blog.gsp under the grails-app/views/layouts folder with the HTML code shown here:

<%@ page contentType="text/html;charset=UTF-8" %>  Groovy Publish - <g:layoutTitle/>  

When you apply this layout to all the GSPs, each page will be decorated with the contents of the layout. When a page with a layout is rendered, the layout will provide the main structure of the page and will pull in the contents of the page it is being used to render using the three available layout tags:

  • layoutTitle: pulls the contents of the HTML </span> tag from the rendered GSP into the layout</li> <li><span class="pf">layoutHead</span>: pulls the contents of the HTML <span class="pf"><head></span> tag from the rendered GSP into the layout</li> <li><span class="pf">layoutBody</span>: pulls the contents of the <span class="pf"><body></span> tag from the rendered GSP</li> </ul> <p>Now that you have the layout defined, you can put the common page elements into it, such as the login and logout links:</p> <pre><code><%@ page contentType="text/html;charset=UTF-8" %><html><head> <title>Groovy Publish - <g:layoutTitle/>

    This updated layout shows a login link if the user is not authenticated and a logout link if the user is authenticated. Notice that there is a link to a CSS for styling. The createLinkTo method tells Grails to look in the css directory under the web-app directory. All static resources, such as CSS, images, and JavaScript files are stored under the web-app directory.

    Testing Time
    Grails provides two types of testing by default: unit and integration (see Sidebar 1. The Difference Between Unit and Integration Tests). If you create domain classes, controllers, and services through the Grails command line, you will automatically have integration tests created for these classes. Test classes can be found in the test directory at the same level as the grails-app directory. All unit and integration tests can be run from the command line by executing this command:

    grails test-app

    Listing 5 shows an integration test for the Post domain class showing the available Grails CRUD operations and also for ensuring that the constraints are working correctly.

    Each test method is named explicitly to add clarity to the thing that is under test. To reduce the verbosity of this approach, a number of utility test methods (field*) have been created using Groovy meta programming. Each of these methods uses the setProperty method provided by the GroovyObject interface.

    Simple Tagging with AJAX
    Grails provides AJAX support through the following set of tags:

    • remoteLink: calls a remote function when the link is clicked
    • remoteField: creates a field that sends updates to the server automatically
    • formRemote: performs AJAX for submission (falling back to normal form submission if JavaScript is not enabled)
    • remoteFunction: assigns a remote JavaScript function to DOM events

    To demonstrate some of these tags, you will add tagging to the blog. To add tagging to posts, you will need to make the changes to the domain shown in Listing 6. The changes to the Post class are highlighted in bold.

    The areas of interest in Listing 6 are the creation of a many-to-many relationship and the use of the "?." operator. The many-to-many relationship is created by having a static hasMany property on the tag and the post. Behind the scenes, Grails will create a linking table in the database to allow this many-to-many relationship to be persisted in the database. The belongsTo property should be put on the post end of the relationship to allow a save() call on a post to cascade to the tags to which the post is related. The "?." operator performs an implicit null check on the object before calling the method or property specified, which avoids having to perform a large number of null checks in the code.

    Next, you need to add a field to the edit.gsp file for posts to enter tags as a space-separated string:


    When this field is in place, the PostController needs to be updated to handle creating tags and displaying posts by tag. Listing 7 also shows the PostService you should create to extract some logic from the controller.

    The PostService is created to extract the loadPost logic that was in the controller and to add the space-delimited list of tags to a Post. Remember that defining the postService property in the controller will automatically inject the PostService. The save action is updated to allow the tags to be added to the post. A new listByTags action is added to allow all posts for a given tag to be loaded. You will notice that this action assumes the ID property in the params map is actually the tag name:

    def tag = Tag.findByName(params.id)

    The reason for this is that you can create meaningful URLs that are readable, such as:


    This URL will show all posts tagged with java, and it is more intuitive than:


    To help with manual testing, you should add some tags to the posts that are created in the BootStrap class (see Listing 8).

    Finally, you need to display tags on the post list page. To do this, you must create a filter that will add the full list of available tags to the model, create a tag to list the tags for a post, and update the post list page to display tags. Listing 9 shows how to do this.

    The tags filter is configured to execute for every action in the site. You use the after closure to add the full list of tags to the model created by the action. You use the "?." operator for this because the model could be null if a redirect is issued. The tag library class will iterate over a list of tags and create a list of space-delimited links to the listByTag action on the post controller. In the list GSP, the webRequest, a Grails-specific request object (GrailsWebRequest), is used to determine which action has rendered this page to determine if the tag name should be displayed. The formatDate tag has been used to improve the readability of the published date of the post, and the new tagLinks tag is used to render the links to the tags for a post. Finally the layout, blog.gsp, must be updated to display the list of available tags on the right of the page:


    • ${tag.name}

    If you run the application now, you will see tags displayed on the list page and you will be able to add tags to and remove tags from a post (see Figure 5) through the post edit page (see Figure 6).

    Figure 5. Post List Page With Tags: You should be able to see tags displayed on the post list page.
    Figure 6. Editing Tags For A Post: You can now add and remove tags for a post through the edit page.

    Improving Tagging with AJAX
    To demonstrate the Grails support for AJAX, you can enrich the management of posts by allowing users to edit tags inline on the post list page. You will need to create two templates and add three new actions to the PostController. The Grails AJAX tags you will use are:

    • remoteLink: to load templates in using AJAX requests
    • formRemote: to allow the changes to the list of tags to be submitted using AJAX

    Templates are used to separate out common chunks of view code into reusable fragments. They are especially useful when working with AJAX, as they allow you to easily replace discreet portions of the view as the result of a request. Templates are similar to views in that they exist in the grails-appviews folder. The convention for naming templates is to create them with an underscore at the start of the filename. Create the two templates _showTags.gsp and _editTags.gsp under the grails-appviewspost directory with the code from Listing 10.

    The showTags template displays the tags for a post as before, but also provides a link that will call the editTags action on the post controller through an asynchronous JavaScript request. The attributes of the remoteLink tag are very similar to the Grails link tag you have used before. The controller, action, and id attributes tell the tag to which action the request must be submitted. The big difference is the update attribute. This tells the AJAX-handling code generated by the tag which HTML element to update with the result of the AJAX request.

    The editTags action will render the editTags template, which creates a form allowing tags to be edited in place of the current list of tags. The editTags template renders a form that will submit its data through an AJAX call. The formRemote tag specifies the URL to submit the asynchronous request to, while the use of the controller and action attributes are the fallback location to submit an HTTP request to in case JavaScript is not enabled. Another remoteLink is used to reload the list of tags if the user wishes to cancel the update.

    To allow the list page to use AJAX, you must include the following in the HTML tag:

    This tells Grails to use the Prototype JavaScript library.

    Additionally, to add the new actions to the controllers, replace the line that currently shows the tags for a post:


    With the following:

    The following are the three new actions to handle updating tags:

    def editTags = {  render(template:"editTags",      model:[post:Post.get(params.id)])}def saveTags = {  def post = postService.loadPost(params.id)  postService.populateTags(post, params.tagString)  if(post.save()) {    render(template:"showTags", model:[post:post])  } else {    render("Save failed")  }}def showTags = {  render(template: 'showTags',      model: [post: Post.get(params.id)])    }

    The editTags action handles the rendering of the editTags template, just as the showTags action renders the showTags template. The saveTags action loads the identified post and adds the tags to the post before saving the post and then rendering the showTags template.

    If you now run the application you should have a link to edit tags on the post list page (see Figure 7). Clicking this link will load a form that allows you to edit the tags inline (see Figure 8).

    Figure 7. Edit Tags Link: Tags can be edited from the post list page.
    Figure 8. Edit Tags Inline: Tags can be edited inline on the post list page.

    Packaging and Deploying the Blog Application
    You now have a blog application that will allow you to create blog posts, receive comments from the readers, publish the details of the posts via RSS, and manage the posts through tagging. It is time to think about deploying it! For this, you need to install Tomcat and MySQL. You will have to package the application as a WAR and tell it which database to access.

    The grails war script will package the application as a WAR. Go to the command line and run this script. It should create a war file called groovypublish-0.1.war. The version number comes from the application.properties file. To generate a WAR without the extension, simply specify the name you would like to call the file after the script command:

    grails war groovypublish.war

    Pick Your Grails Environments
    Grails has a built in notion of environments. The default environments it understands are development, test, and production. A Grails application will always run within the context of a particular environment. The default when running grails run-app is the development environment. The default when running grails war is the production environment. It is possible to change these defaults by specifying the environment before the script to run. The following script:

    grails prod run-app

    Will run the application in production mode, while this script:

    grails dev war 

    will run the application in development mode.You can also create your own environments and run Grails under them using the grails.env system property. This script:

    grails –Dgrails.env=uat run-app 

    Would run the grails application in UAT mode.

    So what do all these environments mean? The biggest affect they have is on the way the application connects to the database. Take a look at DataSource.groovy in the conf directory. If you haven't modified this already, it will look something like Listing 11.

    The dataSource setup at the top of the DataSource.groovy file is the common data source configuration for all environments. You can see that the other "environmental" data sources specify only the dbCreate and url properties. The dbCreate property is the only one here that is specific to Grails rather than a JDBC data source. It offers three database modes:

    • create-drop: this drops and recreates the database when the application is started.
    • create: this creates the database if it does not exist, and deletes the existing data if a database does exist.
    • update: this creates the database if it does not exist and modifies the structure of it if it does exist.

    The only option that does not delete all the data in the database is update. Make sure you use this when you deploy the application. Notice that the production environment comes in update mode by default.

    In the example above, Grails was run in UAT mode by using the grails.env system property. If you wanted to set up a database for this environment, you could add the following to the DataSource.groovy file:

    uat {  dataSource {    dbCreate = "update"    url = "jdbc:hsqldb:mem:uatDb"  }}

    The Hibernate properties specified in this script can also be environmentally aware. If you wanted to enable SQL logging in development only, then you could add the following:

    development {  dataSource {    dbCreate = "create-drop" // one of 'create', 'create-drop','update'    url = "jdbc:hsqldb:mem:devDB"  }  hibernate {    show_sql=true  }}

    Using a Real Database
    Install MySQL and create a database like so:

    CREATE database groovypublish;GRANT ALL PRIVILEGES ON groovypublish.* TO 'groovypublish'@'localhost'IDENTIFIED BY 'groovypublish' WITH GRANT OPTION;

    This will give you a database called groovypublish with a user called groovypublish and a password of groovypublish. When configuring the Tomcat instance, you should set up the data source in JNDI. This allows the container to manage the database connection rather than having to specify these details in the application. Create a JNDI data source called groovyPublish/dataSource and configure the Grails application to use this data source when running in production mode by updating the DataSource.groovy script:

    production {  dataSource {    dbCreate = "update"    jndiName = "java:comp/env/groovyPublish/dataSource"  }}

    If you now repackage the application and drop the WAR into Tomcat, you should be able to access the application through Tomcat directly.

    Controlling BootStrap
    One last change needs to be made to the BootStrap script, which is to allow it to run only in development. Otherwise, it will run every time you try to start Tomcat. You can simply wrap the bootstrap code with this:

    if(grails.util.GrailsUtil.environment == "development") {...}

    Tapping the Power of Groovy and Grails
    You have now created and deployed a blog application. You obviously can make further improvements to the application, but you can see just how powerful Grails is and how easy it is to build applications using Groovy and Grails. The code used for these articles has formed the basis of an open source project that I intend to continue. To see how it progresses, or to get involved, contact me or take a look at the site.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: