Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Grails 1.1 Web Application Development
Grails 1.1 Web Application Development

Grails 1.1 Web Application Development: Reclaiming Productivity for faster Java Web Development

By Jon Dickinson
$25.99 $17.99
Book May 2009 328 pages 1st Edition
eBook
$25.99 $17.99
Print
$43.99
Subscription
$15.99 Monthly
eBook
$25.99 $17.99
Print
$43.99
Subscription
$15.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : May 27, 2009
Length 328 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781847196682
Category :
Table of content icon View table of contents Preview book icon Preview Book

Grails 1.1 Web Application Development

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.

Left arrow icon Right arrow icon

Key benefits

  • Ideal for Java developers new to Groovy and Grailsóthis book will teach you all you need to create web applications with Grails
  • Create, develop, test, and deploy a web application in Grails
  • Take a step further into Web 2.0 using AJAX and the RichUI plug-in in Grails
  • Packed with examples and clear instructions to lead you through the development and deployment of a Grails web application

Description

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.

What you will learn

Understand the relationship between Grails and the Groovy scripting language Learn enough about Groovy to get you writing your first Grails applications Use the built-in AJAX support to enhance user interaction and create slick user interfaces with the RichUI plug-in Develop and use a REST service interface and provide an API through REST Handle file upload and versioning allowing users to share files Use Grails scaffolding to generate a user interface to allow management of users and roles within the application. Secure your application with the JSecurity plug-in and use plug-ins to solve common problems Reduce object persistence issues using Grails Object-Relational Mapper Create your own Grails plug-in for tagging to limit the amount of data that is displayed on your home page Get to grips with automated testing to write functional tests that drive the application Expose your application to other developers with a RESTful API

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : May 27, 2009
Length 328 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781847196682
Category :

Table of Contents

20 Chapters
Grails 1.1 Web Application Development Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the author Chevron down icon Chevron up icon
Acknowledgement Chevron down icon Chevron up icon
About the reviewers Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
Getting Started with Grails Chevron down icon Chevron up icon
Managing Users with Scaffolding Chevron down icon Chevron up icon
Posting Messages Chevron down icon Chevron up icon
Introduction to Groovy Chevron down icon Chevron up icon
Authentication with JSecurity Plug-in Chevron down icon Chevron up icon
Testing Chevron down icon Chevron up icon
File Sharing Chevron down icon Chevron up icon
More GORM and Criteria Chevron down icon Chevron up icon
Services Chevron down icon Chevron up icon
Managing Content through Tagging Chevron down icon Chevron up icon
AJAX and RIA Frameworks Chevron down icon Chevron up icon
Searching, RSS, and REST Services Chevron down icon Chevron up icon
Build your own Plug-in Chevron down icon Chevron up icon
Deployment and the Real World Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.