Grails (framework)

Grails (framework)

Infobox Software
name = Grails



caption =
author =
developer =
released =
latest release version = 1.0.3
latest release date = release date|2008|6|6
operating system = Cross platform
platform = Cross platform (JVM)
language =
programming language = Groovy
genre = Web application framework
license = Apache License 2.0
website = http://grails.org

Grails is an open source web application framework which leverages the Groovy programming language (which is in turn based on the Java platform). Grails is intended to be a high-productivity framework by following the "coding by convention" paradigm, providing a stand-alone development environment and hiding much of the configuration detail from the developer.

Grails was previously known as 'Groovy on Rails' (the name was dropped in response to a request by David Heinemeier Hansson, founder of the Ruby on Rails framework. [ [http://www.nabble.com/Groovy-on-Rails-is-no-more-%28kind-of%29-t1369271.html Dropping Groovy on Rails name] ] ). Work began in July 2005, with the 0.1 release on March 29 2006 and the 1.0 release announced on February 18 2008.

Overview

Grails has been developed with a number of goals in mind:

* Provide a high-productivity web framework for the Java platform.
* Re-use proven Java technologies such as Hibernate and Spring under a simple, consistent interface
* Offer a consistent framework which reduces confusion and is easy to learn.
* Offer documentation for those parts of the framework which matter for its users.
* Provide what users expect in areas which are often complex and inconsistent:
** Powerful and consistent persistence framework.
** Powerful and easy to use view templates using GSP (Groovy Server Pages).
** Dynamic tag libraries to easily create web page components.
** Good Ajax support which is easy to extend and customize.
* Provide sample applications which demonstrate the power of the framework.
* Provide a complete development mode, including web server and automatic reload of resources.

Grails has been designed to be easy to learn, easy to develop applications and extensible. It attempts to offer the right balance between consistency and powerful features.

High productivity

Grails has three properties which increase developer productivity significantly when compared to traditional Java web frameworks:

* No XML configuration
* Ready-to-use development environment
* Functionality available through mixins

No XML configuration

Creating web applications in Java traditionally involves configuring environments and frameworks at the start and during development. This configuration is very often externalized in XML files to ease configuration and avoid embedding configuration in application code.

XML was initially welcomed as it provided greater consistency to configure applications. In recent years however it has become apparent that although XML is great for configuration it can be tedious to set up an environment. This may take away productivity as developers spend time understanding and maintaining framework configuration as the application grows. Adding or changing functionality in applications which use XML configuration adds an extra step to the change process next to writing application code which slows down productivity and may take away the agility of the entire process.

Grails takes away the need to add configuration in XML files. Instead the framework uses a set of rules or conventions while inspecting the code of Grails-based applications. For example, a class name which ends with Controller (for example BookController) is considered a web controller.

Ready-to-use development environment

When using traditional Java web toolkits, it's up to developers to assemble deployment units which can be tedious. Grails comes with a complete development environment which includes a web server to get developers started right away. All required libraries are part of the Grails distribution and Grails prepares the Java web environment for deployment automatically.

Functionality available through mixins

Grails features dynamic methods on several classes through mixins. A mixin is functionality (in the case of Grails mixins are methods) which is added to classes dynamically as if the functionality is compiled in the program.

These dynamic methods allow developers to perform operations without having to implement interfaces or extend base classes. Grails provides dynamic methods based on the type of class. For example domain classes have methods to automate persistence operations like save, delete and find.

Web framework

The Grails web framework has been designed according to the MVC paradigm.

Controllers

Grails uses controllers to implement the behaviour of web pages. Below is an example of a controller: class BookController { def list = { [ books: Book.findAll() ] } }The controller above has a list action which returns a model containing all books in the database. To create this controller the grails command is used, as shown below:

grails create-controller

This command requests the controller name and creates a class in the grails-app/controller directory of the Grails project. Creating the controller class is sufficient to have it recognized by Grails. The list action maps to http://localhost:8080/book/list in development mode.

Views

Grails supports JSP and GSP. The example below shows a view written in GSP which lists the books in the model prepared by the controller above:

Our books

  • ${it.title} (${it.author.name})

This view should be saved as grails-app/views/book/list.gsp of the Grails project. This location maps to the BookController and list action. Placing the file in this location is sufficient to have it recognized by Grails.

There is also a [http://docs.codehaus.org/display/GRAILS/GSP+Tag+Reference GSP tag reference] available.

Ajax support

Grails supports several Ajax libraries including OpenRico, Prototype and Yahoo! UI library [ [http://developer.yahoo.com/yui/ Yahoo! UI library] ] . You can use existing tag libraries which create HTML with Ajax code. You can also easily create your own tag libraries.

Dynamic tag libraries

Grails provides a large number of tag libraries out of the box. However you can also create and reuse your own tag libraries easily: def formatDate = { attrs -> out << new java.text.SimpleDateFormat(attrs.format).format(attrs.date) }The formatDate tag library above formats a Javadoc:SE|java/util|package=java.util|Date object to a Javadoc:SE|java/lang|String. This tag library should be added to the grails-app/taglib/ApplicationTagLib.groovy file or in a file ending with TagLib.groovy in the grails-app/taglib directory.

Below is a snippet from a GSP file which uses the formatDate tag library:

To use a dynamic tag library in a GSP no import tags have to be used. Dynamic tag libraries can also be used in JSP files although this requires a little more work. [http://grails.codehaus.org/Dynamic+Tag+Libraries]

Persistence

Model

The domain model in Grails is persisted to the database using [http://grails.codehaus.org/GORM GORM] (Grails Object Relational Mapping). Domain classes are saved in the grails-app/domain directory and can be created using the grails command as shown below:

grails create-domain-class

This command requests the domain class name and creates the appropriate file. Below the code of the Book class is shown: class Book { String title Person author }Creating this class is all that is required to have it managed for persistence by Grails. With Grails 0.3, GORM has been improved and e.g. adds the properties id and version itself to the domain class if they are not present.

Methods

The domain classes managed by GORM have 'magic' dynamic and static methods to perform persistence operations on these classes and its objects. [http://grails.codehaus.org/DomainClass+Dynamic+Methods]

Dynamic Instance Methods

The save() method saves an object to the database: def book = new Book(title:"The Da Vinci Code", author:Author.findByName("Dan Brown")) book.save()The delete() method deletes an object from the database: def book = Book.findByTitle("The Da Vinci Code") book.delete()The refresh() method refreshes the state of an object from the database: def book = Book.findByTitle("The Da Vinci Code") book.refresh()The ident() method retrieves the objects identity assigned from the database: def book = Book.findByTitle("The Da Vinci Code") def id = book.ident()

Dynamic Static (Class) methods

The count() method returns the number of records in the database for a given class: def bookCount = Book.count()The exists() method returns true if an object exists in the database with a given identifier: def bookExists = Book.exists(1)The find() method returns the first object from the database based on an object query statement: def book = Book.find("from Book b where b.title = ?", [ 'The Da Vinci Code' ] )Note that the query syntax is Hibernate HQL.

The findAll() method returns all objects existing in the database: def books = Book.findAll()The findAll() method can also take an object query statement for returning a list of objects: def books = Book.findAll("from Book")The findBy*() methods return the first object from the database which matches a specific pattern: def book = Book.findByTitle("The Da Vinci Code")Also: def book = Book.findByTitleLike("%Da Vinci%")The findAllBy*() methods return a list of objects from the database which match a specific pattern: def books = Book.findAllByTitleLike("The%")The findWhere*() methods return the first object from the database which matches a set of named parameters: def book = Book.findWhere(title:"The Da Vinci Code")

Scaffolding

Grails supports scaffolding to support CRUD operations (Create, Read, Update, Delete). Any domain class can be scaffolded by creating a scaffolding controller as shown below: class BookController { scaffold = true }By creating this class you can perform CRUD operations on http://localhost:8080/book. Currently Grails does not provide scaffolding for associations.

Legacy Database Models

The persistence mechanism in GORM is implemented via Hibernate. As such, legacy databases may be mapped to GORM classes using standard [http://grails.codehaus.org/Hibernate+Integration Hibernate mapping] files.

Creating a Grails project

A Grails project is created as follows:

* Follow the download and installation guidelines on the Grails web site. [http://grails.codehaus.org/Installation]
* Open a command prompt and type:

grails create-app

This command will request the name of the project and will create a project directory with the same name. Change to this directory to use the grails command.

By running the grails run-app you can now try the http://localhost:8080/ URL.

Target audience

The target audience for Grails is:

* Java developers who are looking for an integrated development environment to create web based applications.
* Developers without Java experience looking for a high-productivity environment to build web based applications.

Integration with the Java platform

Grails is built on top of and is part of the Java platform meaning it's very easy to integrate with Java libraries, frameworks and existing code bases. The most prominent feature Grails offers in this area is the transparent integration of classes which are mapped with the Hibernate ORM framework. This means existing applications which use Hibernate can use Grails without recompiling the code or reconfiguring the Hibernate classes while using the dynamic persistence methods discussed above. [http://grails.codehaus.org/Hibernate+Integration]

One consequence of this is that scaffolding can be configured for Java classes mapped with Hibernate. Another consequence is that the capabilities of the Grails web framework are fully available for these classes and the applications which use them.

References

See also

* JRuby

External links

* [http://grails.codehaus.org Grails home page]
* [http://groovy.codehaus.org Groovy home page]
* [http://grails.org/Grails+Screencasts Grails Screencasts]
* [http://www.ociweb.com/jnb/jnbMar2007.html Introduction To Grails] , by Jeff Brown, Principal Software Engineer, Object Computing, Inc. (OCI)
* [http://www.infoq.com/minibooks/grails Getting Started with Grails] , by Jason Rudolph, as part of the InfoQ Enterprise Development series of books - available as a free PDF download to registered users
* [http://www.holygrails.net Grails Tutorials] fresh grails posts, from the blogosphere, with code snippets and tutorials to get started quickly
* [http://www.visualbuilder.com/jsp/grails/tutorial/ Grails Tutorial] Gentle introduction to Grails


Wikimedia Foundation. 2010.

Игры ⚽ Нужно решить контрольную?

Look at other dictionaries:

  • Grails — may refer to:* Grails (band), are an American instrumental rock band. * Grails (framework), is an open source web application framework for high productivity …   Wikipedia

  • Grails — ? Información general Última versión estable 1.3.7 17 de febrero de 2011 Género Framework de aplicaciones web …   Wikipedia Español

  • Grails (technologie) — Pour les articles homonymes, voir Grails. Grails (technologie) Développeu …   Wikipédia en Français

  • Grails — Тип программный каркас для создания веб приложений Разработчик Steven Devijver, Graeme Rocher Написана на Groovy Операционная система кроссп …   Википедия

  • Grails — Basisdaten Aktuelle Version 1.3.7 (17. Februar 2011) Betriebssystem …   Deutsch Wikipedia

  • Grails (technique) — Pour les articles homonymes, voir Grails. Grails (technique) Développeurs Gr …   Wikipédia en Français

  • Framework —  Pour l’article homonyme, voir Framework (logiciel).  Sur les autres projets Wikimedia : « Framework », sur le Wiktionnaire (dictionnaire universel) En programmation informatique, un framework est un kit de composants… …   Wikipédia en Français

  • Framework — Ein Framework (englisch für „Rahmenstruktur“ oder „Fachwerk“) ist ein Programmiergerüst, das in der Softwaretechnik, insbesondere im Rahmen der objektorientierten Softwareentwicklung sowie bei komponentenbasierten Entwicklungsansätzen, verwendet… …   Deutsch Wikipedia

  • Grails — Cette page d’homonymie répertorie les différents sujets et articles partageant un même nom. Grails est un framework open source basé sur Groovy. Grails est un groupe de musique de Portland. Catégorie : Homonymie …   Wikipédia en Français

  • Griffon (framework) — Infobox Software name = Griffon caption = author = developer = released = latest release version = 0.0.1 latest release date = operating system = Cross platform platform = Cross platform (JVM) language = programming language = Groovy genre = Rich …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”