Grails 1.1 Web Application Development

By Jon Dickinson
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Getting Started with Grails

About this book

Web development is tricky—even a simple web application has a number of context changes ready to trip up the unwary. Grails takes the everyday pain out of web application development, allowing us to focus on delivering real application logic and create seamless experiences that will address the needs of our users. This book will take the pain out of Grails by showing you exactly how to build a web application with a minimum of fuss.

With this book, even if you are new to Grails, you will be up and running before you know it. You will be able to code faster and your code will be better. This clear and concise book is packed with examples and clear instructions to help you build your first Grails application and gives you the skills to speed up your application development by adding a different angle for learning about the topic. After a brief introduction to the dynamic JVM-based Groovy programming language, which teaches you enough about Groovy to understand the relationship between Grails and the Groovy scripting language, it shows how to use Grails and a number of key plug-ins to deliver valuable web applications. It also takes you through creating, developing, testing, and deploying an example team collaboration application in Grails.

Using an incremental and iterative approach you will learn how to build a basic web application with secure authentication and different levels of authorization. You will learn how to handle file upload allowing users to share files. Some advanced features of object-oriented persistence will be introduced through adding tags for messages and files to giving users a robust categorization system.

You will then build on the basic application to enhance the user experience through AJAX and the RichUI plug-in. You will take a further step into the world of Web 2.0 by adding an RSS feed and a REST service to the application. Once the entire application is up and running, you will learn how to create your own plug-in for tagging. Finally, you will learn how to deploy this application to a production environment.

Publication date:
May 2009
Publisher
Packt
Pages
328
ISBN
9781847196682

 

Chapter 1. Getting Started with Grails

Grails is a dynamic web development framework on the Java platform for rapid application development. It has taken the coding by convention approach popularized by Ruby on Rails, and applied it as a wrapper over long established open source Java frameworks such as Hibernate and Spring. It uses the flexibility of Groovy to provide a Domain-Specific Language (DSL) for web development.

The goal is to be able to develop web applications with the minimum amount of effort without having to repeat yourself. Grails provides a consistent and reliable environment between all of your projects.

Why Grails?

Web development is a tricky business. Even a simple web application has a number of context changes ready to trip up the unwary developer. HTTP requests must be parsed and converted into internal code representations. Once parsed, the data must be validated to make sure no invalid or dangerous information has been sent. The data extracted from these requests is then persisted to rows in database tables. To send a response back to the user, data must be retrieved from the database and converted into the domain model. It is then rendered from the domain model into HTML format and sent back over HTTP. With every user action going through all these different conversions, we can see how web development can become expensive, and this is just the server side. We haven't even considered all the client-side coding that goes into web applications with the rich user experiences that are becoming the norm in the Web 2.0 era.

Over the years, there have been a number of frameworks created to alleviate the cost of building web applications. Web frameworks such as Struts, Spring MVC, Stripes, and JSF help in mapping the HTTP requests to code logic. Object to relational database mapping frameworks allow domain objects to be persisted directly to the database, Hibernate being the most notable. These frameworks have allowed larger and more complicated web applications to be implemented by reducing the workload of the application developer. Unfortunately, a side effect of multiple frameworks is an increased level of configuration that needs to be produced and maintained. The level of knowledge required to create framework configuration files is probably less than writing the code. However, it is notoriously difficult to debug and test the configuration.

Grails helps application developers provide value faster by:

  • Requiring less configuration

  • Faster setup

  • Shorter develop/test cycle

  • Consistent development environment

  • Domain-specific language for web development

  • Fewer dependencies

Less configuration

The first benefit Grails provides is a convention-based approach to remove the need for reams of configuration, while still leveraging the power of the mature underlying frameworks. In practice, this means that you don't spend a lot of time wiring your code together in XML configuration files, or muddy your code with endless annotations. Instead, if a class is created, according to the convention in the correct location, it will be wired into Spring as needed or will be treated as a Hibernate entity ready to be persisted in the database.

Faster setup

The convention based approach applies to your development environment as well as the code. As soon as you create a Grails project, you have a defined structure and a set of scripts already available to compile, test, run and package your project. Having all these scripts managed in a consistent and conventional manner greatly reduces the time required to get a project up and running.

Grails also comes configured with a bundled database and application server. So once you have Grails installed, and your project created, there is nothing else you need before you start development.

No longer do you need to spend time setting up a development environment for each project. Tweaking your Ant build scripts slightly for each new environment is a thing of the past, and so is configuring an application and database server for development.

Shorter develop/test cycle

Grails uses a bundled Jetty (http://www.mortbay.org/jetty/) installation for the application server, which is configured to execute against the working code base of your application. Grails is also built on top of Groovy — a dynamic language for the JVM that adds powerful new features to Java. Groovy compiles down to the Java bytecode, which allows it to integrate with any existing Java code. Chapter 4 introduces you to the Groovy language, if you have not used it before.

In development mode, Grails provides an auto-reloading feature (http://www.grails.org/Auto+Reloading), which allows you to make changes to your code and see the changes in your browser with the next refresh. There is no need to restart the application, or to re-deploy to an application server.

Consistent development environment

It is best practice in software development to try and ensure that all developers in a project are working in the same way and have a common environment on each machine. In reality, there are often conflicts between the configurations of different team member's development environments; team members may configure their application servers differently or use different database versions. You can waste valuable time debugging false problems in your software just because another team member has a configuration slightly different from yours.

Grails comes with a pre-defined application structure. This ensures that all developers will be working in the same way with the same environment configuration.

Domain-specific language for web development

Any experienced Java web developer will be familiar with the Servlet Specification, which provides a standard set of interfaces for working with HTTP. Grails builds on this specification and provides a DSL for developing web applications. The underlying specification is still available to developers, if they wish to use it, but in- depth knowledge is no longer required. By leveraging the flexibility of the Groovy language, Grails provides an intuitive and simple domain language specific to the web development, upon which you can build great web applications.

Fewer dependencies

The cost of getting up and running with Grails is remarkably low. You will need to download and install the following:

  • Java 1.5 or greater

  • Grails 1.1 or greater

Note that there is no need to download Groovy; it comes bundled with the Grails download.

Compare this to getting set up on a normal Java web project, where the typical download and install list would look something like this:

  • Java

  • DB server (for example, MySQL, HSQL DB)

  • Application server (for example, Tomcat)

  • Hibernate

  • Spring

  • Web framework (for example, Struts, Spring MVC)

  • View rendering framework (for example, Velocity, Freemarker)

  • Logging framework (for example, commons logging and Log4J)

You will eventually need to download and install an application server and a database server. Fortunately, this work can be put off until later down the line when you are thinking about deployment.

 

Why Grails?


Web development is a tricky business. Even a simple web application has a number of context changes ready to trip up the unwary developer. HTTP requests must be parsed and converted into internal code representations. Once parsed, the data must be validated to make sure no invalid or dangerous information has been sent. The data extracted from these requests is then persisted to rows in database tables. To send a response back to the user, data must be retrieved from the database and converted into the domain model. It is then rendered from the domain model into HTML format and sent back over HTTP. With every user action going through all these different conversions, we can see how web development can become expensive, and this is just the server side. We haven't even considered all the client-side coding that goes into web applications with the rich user experiences that are becoming the norm in the Web 2.0 era.

Over the years, there have been a number of frameworks created to alleviate the cost of building web applications. Web frameworks such as Struts, Spring MVC, Stripes, and JSF help in mapping the HTTP requests to code logic. Object to relational database mapping frameworks allow domain objects to be persisted directly to the database, Hibernate being the most notable. These frameworks have allowed larger and more complicated web applications to be implemented by reducing the workload of the application developer. Unfortunately, a side effect of multiple frameworks is an increased level of configuration that needs to be produced and maintained. The level of knowledge required to create framework configuration files is probably less than writing the code. However, it is notoriously difficult to debug and test the configuration.

Grails helps application developers provide value faster by:

  • Requiring less configuration

  • Faster setup

  • Shorter develop/test cycle

  • Consistent development environment

  • Domain-specific language for web development

  • Fewer dependencies

Less configuration

The first benefit Grails provides is a convention-based approach to remove the need for reams of configuration, while still leveraging the power of the mature underlying frameworks. In practice, this means that you don't spend a lot of time wiring your code together in XML configuration files, or muddy your code with endless annotations. Instead, if a class is created, according to the convention in the correct location, it will be wired into Spring as needed or will be treated as a Hibernate entity ready to be persisted in the database.

Faster setup

The convention based approach applies to your development environment as well as the code. As soon as you create a Grails project, you have a defined structure and a set of scripts already available to compile, test, run and package your project. Having all these scripts managed in a consistent and conventional manner greatly reduces the time required to get a project up and running.

Grails also comes configured with a bundled database and application server. So once you have Grails installed, and your project created, there is nothing else you need before you start development.

No longer do you need to spend time setting up a development environment for each project. Tweaking your Ant build scripts slightly for each new environment is a thing of the past, and so is configuring an application and database server for development.

Shorter develop/test cycle

Grails uses a bundled Jetty (http://www.mortbay.org/jetty/) installation for the application server, which is configured to execute against the working code base of your application. Grails is also built on top of Groovy — a dynamic language for the JVM that adds powerful new features to Java. Groovy compiles down to the Java bytecode, which allows it to integrate with any existing Java code. Chapter 4 introduces you to the Groovy language, if you have not used it before.

In development mode, Grails provides an auto-reloading feature (http://www.grails.org/Auto+Reloading), which allows you to make changes to your code and see the changes in your browser with the next refresh. There is no need to restart the application, or to re-deploy to an application server.

Consistent development environment

It is best practice in software development to try and ensure that all developers in a project are working in the same way and have a common environment on each machine. In reality, there are often conflicts between the configurations of different team member's development environments; team members may configure their application servers differently or use different database versions. You can waste valuable time debugging false problems in your software just because another team member has a configuration slightly different from yours.

Grails comes with a pre-defined application structure. This ensures that all developers will be working in the same way with the same environment configuration.

Domain-specific language for web development

Any experienced Java web developer will be familiar with the Servlet Specification, which provides a standard set of interfaces for working with HTTP. Grails builds on this specification and provides a DSL for developing web applications. The underlying specification is still available to developers, if they wish to use it, but in- depth knowledge is no longer required. By leveraging the flexibility of the Groovy language, Grails provides an intuitive and simple domain language specific to the web development, upon which you can build great web applications.

Fewer dependencies

The cost of getting up and running with Grails is remarkably low. You will need to download and install the following:

  • Java 1.5 or greater

  • Grails 1.1 or greater

Note that there is no need to download Groovy; it comes bundled with the Grails download.

Compare this to getting set up on a normal Java web project, where the typical download and install list would look something like this:

  • Java

  • DB server (for example, MySQL, HSQL DB)

  • Application server (for example, Tomcat)

  • Hibernate

  • Spring

  • Web framework (for example, Struts, Spring MVC)

  • View rendering framework (for example, Velocity, Freemarker)

  • Logging framework (for example, commons logging and Log4J)

You will eventually need to download and install an application server and a database server. Fortunately, this work can be put off until later down the line when you are thinking about deployment.

 

Installing Grails


Now that you have had the salesman's pitch for Grails, it's time to see if it can live up to the hype. So, let's get started.

Download Grails from http://www.grails.org and extract the downloaded files to your development folder. Create an environment variable called GRAILS_HOME and point it to the extract location.

You will then need to add the %GRAILS_HOME%/bin to your path. It's that easy!

While working on a Mac, you can modify the environment.plist file in the .MacOSX directory as shown in the following screenshot:

Although Grails is built on top of Groovy, there is no need to install Groovy separately. Grails comes with the groovy-all-x.x.x.jar bundled and executes your Groovy code directly.

The first step is to create a new Grails application with the Grails script, ' create-app'. You will create a new application called 'teamwork'. Open up your command line, go to your development area and run:

>grails create-app teamwork

You should see something like the following output:

Welcome to Grails 1.1 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: /tools/grails-1.1
...
Created Grails Application at <your_development_location>/teamwork

This will create a folder called teamwork and will set up your application structure within this folder. Verify that the application has been configured correctly. Go to the teamwork directory and check that you have a folder structure as shown in the following screenshot:

The grails-app folder will contain the main source code for your application. By examining the layout of this folder, you can see the beginnings of the convention for the layout of your application. The Model View Controller (MVC) (http://java.sun.com/blueprints/patterns/MVC-detailed.html) pattern is enforced through this convention.

Here is the breakdown of the layout:

  • The domain directory contains the Model classes.

  • The views directory contains the view code.

  • The controller directory contains the controller files.

  • The conf directory contains any configuration code that we need to implement.

  • The i18n directory contains message bundles to support internationalization.

  • Helper services will reside in the classes that go into the services directory.

  • Tag libraries, which are refreshingly trivial to be implemented in Grails, reside in the taglib directory.

Once you have confirmed that the structure of your project directory is correct, go into the teamwork directory in your command line and run:

>grails run-app

Wait for the message, Server running. Browse to http://localhost:8080/teamwork, to appear in your command line. Then you can open a browser, and you will see the default Grails start page as shown in the following screenshot:

This is an equivalent of your "Hello World" example, when using any other framework. The result is a Java application server running on port 8080 with your application deployed to the context teamwork. This is not bad going for a five-minute job.

Grails comes with Jetty and HSQLDB already configured, which is why we have been able to get an application up and running so quickly. Jetty is a Java application server that can be ran as an embedded component within any Java application. HSQLDB is a lightweight Java SQL database engine that can be run in-memory with minimal configuration.

Grails applications are packaged as a WAR file for deployment, and so, are not limited to running under Jetty. But developing in this environment provides several benefits including:

  • Fast deployment time

  • Pre-configured setup

  • Automatic reloading of code changes during development

 

Build a team communication portal


Now that we have installed Grails and the default page is up and running, it is time to start creating our application. The aim of this book is to build a communication portal for teams. The application will allow team members to share messages and files with the rest of the team. You will need to implement the following:

  • Manage the users of the application

  • Control access

  • Allow users to send messages

  • Allow team members to share files

  • Improve organization of data through tagging

  • Add an XML API via a REST (Representational State Transfer) web service

  • Allow messages and files to be searched

  • Add RSS feeds

Once you have finished implementing the application, you will see how to deploy the application into a production environment using Tomcat and MySQL.

Finally, you will finish up with some additional areas to consider and investigate further, which have not been discussed in this book.

 

Summary


There is a common set of problems associated with web development. There has been a constant progression of frameworks that have gradually made life easier for web developers by pulling more and more common tasks into framework code, allowing us to focus on the implementation of application logic. Grails is the next link in the chain. It applies a Domain-specific language for web development to the most mature and popular frameworks and enforces some best practices along the way.

By setting up the Grails version of the "Hello World" application, we have seen that the cost of setting up your development environment is almost nonexistent. In the next chapter, we will see how to use the power of scaffolding to perform basic user management tasks without having to write any logic at all.

About the Author

  • Jon Dickinson

    Jon Dickinson is the principal consultant and founder of Accolade Consulting Ltd. (http://www.accolade-consulting.co.uk) and can be contacted at [email protected] He specializes in developing web applications on the Java platform to meet the goals of users in the simplest and least obtrusive way possible.

    Browse publications by this author
Book Title
Access this book, plus 7,500 other titles for FREE
Start FREE trial