04 - Grails Model View Controller pattern

Grails MVC (Model / View / Controller) Pattern

Grails follows a very popular pattern in web applications development, called Model – View – Controller. The pattern organizes the software in 3 layers:

Model or data layer: contains all the components that represents and manage data stored in our application.

View or presentation layer: the components in this layer are responsible for showing to the user the state of our data models, and also the actions that they can execute.

Controller or control layer: contains the components that receive orders from the user, manage the business logic over the data model and decide which view should be displayed.

Model

In Grails, data models are defined using what are called “domain classes”, which you could have already learned by the name Entities.

Grails comes with a persistence manager based on Hibernate, called GORM (Grails Object Relational Mapping), which manages entities life cycles and provides default searching methods.

As said before, GORM is based on Hibernate, a popular Object-Relational Mapping (ORM) tool which provides a framework to map object oriented entities to relational database. Every operation performed over a domain class will be translated by Hibernate into any necessary SQL query to reflect the performed operation in the database.

All domain classes of our application are generated in the “domain” folder within our application folder structure.

View

In Grails, views are developed using Groovy Server Pages (GSP), which is a simplified JSP version allowing to place expressions within HTML code and use JSTL like tags.

When our application is running, we can decide which view should be processed and send to the client by means of the “render” method in the controllers or we can let grails to use a default view.

All the views of our applications are generated in the “views” folder within our application folder structure.

Controller

In Grails, controllers are the components responsible for handling incoming client requests, managing the execution of the business logic and updating the view so the user the can know the final status of the data model upon the execution of the action.

The convention in Grails is that any class in the “controller” folder of our application structure and with the name ending in “Controller” will be considered a controller by our application.

Grails will identify upon each HTTP request, which controller it should call based on the definition set in “conf/UrlMappings.groovy”.

Default configuration is set by defining URIs with the following format:

“[controller]/[action]/[id]”

Where:

- “controller” is the first part of the name of our controller (removing the “Controller” suffix).

- “action” is the method to be executed

- “id” is the identifier of an domain-class instance

 

Like us on Facebook