RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Build Your First Grails Project: A Grails-Powered Blog : Page 5

Need to clear out the clutter of your Java web development? Say hello to coding by convention with Grails.

Add Comments
The last thing you need to do for your basic blog is to allow people to add comments. To do this you will need to:
  • Update your CommentController.
  • Create an edit.gsp in the grails-app/views/comment directory.
  • Display comments on the view post page.

The CommentController needs to have only edit and save actions, as comments will be viewed in the context of a post. The Controller in Listing 4 provides a new Comment to the edit form and then saves the comment once it is submitted.

The CommentController contains two new items of interest. The first is the content of the params object when a new Comment is created. This params object will contain value key pairs with the following structure:

  • comment: the users comment
  • who.name: the name of the person leaving the comment
  • who.email: the email of the commentator
  • who.url: the website address of the commentator

This structure will populate the fields of the Comment and its Commentator object. Be aware that you are saving only the comment object and the commentator is being implicitly saved because it belongs to the comment.

The comment edit page is again very basic (see Listing 5).

Finally, you need to add some code to the view.gsp for Posts to allow the comments for a post to be displayed:

<g:each in="${post.comments}" var="comment">
    <div class="comment">
    <p>Made by: ${comment.who.name} on ${comment.dateCreated}</p>

You now have a simple functional blog application, written in under 250 lines of code. In fact, the source code is about 120 lines, including the HTML. This line count does not include any configuration files, because there aren't any. This is the power of Grails. It leverages the coding by convention paradigm to give you access to robust and mature Java open source frameworks such as Spring and Hibernate.

Now that you understand the basics of Grails, be on the lookout for the follow-up article: a look at some more Groovy Grails features, along with instructions for preparing the application for a production environment.

Jon Dickinson is the principal consultant at Accolade Consulting. He focuses on helping organizations improve the software they deliver through agile development techniques.
Email AuthorEmail Author
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date