• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

Grails MVC Tutorial

June 24, 2014 //  by Mohmmad Amr//  Leave a Comment

Grails is an MVC platform that’s used for developing MVC applications. Grails has supported the MVC architecture inherently. This tutorial walk you through the simple example for writing the Grails application using its MVC design pattern. It is for providing you detailed steps for making an MVC applications using the Grails and its GGTS suite that is already installed and configured in our previous tutorial.

We assume that you’ve the setup of Grails platform and GGTS suite installed and configured properly into your environment for writing the Grails MVC example as explained in this tutorial.

also read:

  • Introduction to Grails
  • Introduction to Groovey / Grails Suite
  • What is GVM?
  • Introduction to Groovy Language

1. Grails MVC

This section explains the architecture and different components used in the Grails MVC application. If you look at the below picture, it shows the request flow on a Grails MVC application.

Grails MVC Architecure

  • Model: Model is a Java object which stores the data that can be used by the controllers and views. Technically, controllers might create a model or may be just process them in some sort of normal operations. Grails provides you a binded mechanism that help you references your model from the grails UI components like g:each.
  • Controller: It is a servlet which handles all the request from the front end. In general, Grails servlet extends Spring’s DispatcherServlet to bootstrap the Grails environment (SimpleGrailsController) for handling the requests. SimpleGrailsController delegates to a class called SimpleGrailsControllerHelper that actually handles the request.
  • View: groovy server pages is responsible for rendering the models. Grails uses GroovyPagesTemplateEngine for rendering of GSP views as those views support the concept of custom tag libraries. You can access the g tags directly within your GSP without any need of importing it. A lot of ready-made tags are provided for your use. Grails g library provides you ability of accessing data binded and domain class associations.

This tutorial will provide you a simple example of how could we make a simple Grails MVC application.

  1. Create domain class.
  2. Create Grails controller.
  3. Create views.
  4. Bind your models to use from your views.
  5. Handling different ways of navigation including use of default action and g:link tag.

The project structure for this tutorial would look like this:

Gails - MVC - Project Directory

2. Create Grails Model

This section of tutorial will help you creating a Car model, let’s getting started with the required steps for doing that.

  • Open your GGTS (Grails Suite) and open your created Grails project.
  • Right click on the domain category and select new->domain class.
  • Inside Grails command wizard, type the name of the domain class you want to create. For our example we’ve typed Car and click finish.
  • You would see a fragment of code like static constraints = {} which added by the Grails in your model.
  • Grails provides an inline validation in the model. Grails domain class can express domain constraints simply by defining a public static property constraints that has a closure as a value. This level is what’s you need, further will be discussed in the next coming tutorials.
  • Define your Car class like any normal Plain Old Groovy Object (POGO), following below Car POGO that conform with the Groovy Beans convention.
  • Groovy also supports building relationships between different classes inside your domain. Relations like Inheritance, associations or aggregations also supported by the Groovy.

Car.groovy

package grails.mvc.example

class Car {
String carName
String carBrand
String productionCountry
String productionYear
}

3. Create Grails Controller

This section provides you the steps required for creating a controller component. The main job of the controller is manipulating the data received from the client and decide whether to delegate the request to another controller, output directly into browser or delegating the request into another view populated with the required models.

Following below the steps required for creating a new controller:

  • Within your Grails project, make sure you are choosing the controller category initially.
  • Right click there and select new -> controller.
  • From within Grails command wizard, type the name of the controller you want to be created.
  • For our example we’ve typed RegisterCarController. A proper name for your controller must be ended with the controller phrase, that would help Grails to discover the controllers conventionally.
  • Click finish results in two files to be created, your controller and its unit test.
  • By default, an index action will be defined there.
  • For defining an action, you need to use def <<actionName>>{} construct.
  • Defining controller properties doesn’t differ from those normally defined inside Groovy beans.

Controller defined below contains custom defined properties as well as those required actions:

RegisterCarController.groovy

package grails.mvc.example

class RegisterCarController {
ArrayList&lt;Car&gt; carList = new ArrayList&lt;Car&gt;();
// Scope static variable used for specifying the scope of the controller
static scope ="session"
// Specify the default action of the RegisterCarController
static defaultAction = "initialize"

def initialize (){
// Default action will lead us into register view
render view:"/registerCar/register";
}

def registerAgain(){
// register again action will lead us into register view
render view:"/registerCar/register";
}

def register() {
// Create new instance of car
Car car = new Car()
// Populate the car instance with those corresponding matched request parameters
car.properties = params
try {
// Add car into list of cars
carList.add(car)
}
catch(Exception e){
// Debug the exception thrown
log.debug("Exception Occured ::", e)
}
// Render the next view
render view:"/viewCars/list",model:[cars:carList]
}
}

Some important points should be noticed right now:

  • RegisterCarController has defined a list of car objects.
  • Grails MVC defines scopes for the controllers, scopes are hash-like objects the used for storing variables. Session, request, params, flash and ServletContext are all of scopes that you may use for your controllers.
  • Static variable scope is that variable used for determining the scope you used for your controller, as you’ve seen in the RegisterCarController, session was used as a scope.
  • Default action can be defined as following: using static defaultAction variable as we’ve did in the RegisterCarController, define an index action and provides no additional actions at the same time or by providing the only one action within your controller.
  • Default action has invoked by the Grails platform when specifies no action in the requested URI as it’s happened in the main page RegisterCarController under available controllers section.
  • Initialize action doesn’t provide any kind of data manipulation, but it delegates the control into register view.
  • RegisterAnother action doesn’t provide any kind of data manipulation, but it delegates the control into register view.
  • Register action does the targeted data manipulation we want, it’s used implicit object params for gathering the request parameters from the submitted form. An implicit conversion has been done by the Grails itself, when assigning params into car.properties, every single property inside car does take its value from the identical parameter. Name of property used for achieve the identification required.
  • Register action uses render phrase for determining the next view and optionally bind the list of cars into cars to be used later in the next view.
  • Grails provide you the ability to use the implicit log object for logging your messages. So, no need for defining the log object to be used. More about logging in future.

4. Create Grails Views

Grails consider the Groovy Server Pages (GSP) as a view technology; GSP is HTML-based with special Tag libraries technology. It’s just like JavaServer Pages (JSP) with major advantage of being Grails tags development process.

Grails suite, provides you the ability of creating views. In our example, you will be creating two views, register and list views are developed for registering a new cars while the latter for viewing them.

Let’s first creating the registration view by following the below steps:

  • From within your Grails project, make sure you’re selecting the views category.
  • Right click and create a folder with name registerCar. (That’s will help us leveraging the determination of controller conventionally as Grails had promised)
  • Into registerCar folder, create a new groovy server page with name register.gsp.

Below the form of the view that would help us registering a new cars:

register.gsp

&lt;%@ page contentType="text/html;charset=UTF-8" %&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/&gt;
&lt;meta name="layout" content="main"/&gt;
&lt;title&gt;Car Registration&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div class="body"&gt;
&lt;g:form action="register"&gt;
&lt;table&gt;
&lt;tr&gt;&lt;td&gt;Car Name:&lt;/td&gt;&lt;td&gt;&lt;input id="carName" name="carName" type="text"/&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Car Brand:&lt;/td&gt;&lt;td&gt;&lt;input id="carBrand" name="carBrand" type="text"/&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Car Production Country:&lt;/td&gt;&lt;td&gt;&lt;input id="productionCountry" name="productionCountry" type="text"/&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;Car Production Year:&lt;/td&gt;&lt;td&gt;&lt;input id="productionYear" name="productionYear" type="text"/&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td colspan="2"&gt;&lt;input value="Register" type="submit"/&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;

&lt;/g:form&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;

Some important tips should be mentioned here:

  • Grails provide you the g Tag library to be used within your Groovy server pages GSP. It’s so integral with the groovy server pages as well as it’s so customizable.
  • We’ve created a submission form by using g:form that will submit to a controller. Grails form component provides you additional attributes like action, controller, params, mapping and others beside the all HTML attributes.
  • In case you’ve eliminated the controller attribute from the form tag, the Grails will consider your GSP directory structure for considering the controller that’s responsible handling the form submission. Your GSP located under registerCar directory as it’s appeared in the directory structure above, so that it will convent your controller name by adding the controller phrase as a suffix into your directory structure that will lead us into registerCarController.
  • We’ve provided list of inputs for gathering the all required data that needed for creating a car object. Those form properties have the same name as those properties defined in the car class. Like that naming would help us leveraging the params implicit object.
  • Input of type submit will help us submitting the form.

Using the same steps above you can create the view of list cars. Follow the below form:

list.gsp

&lt;%@ page contentType="text/html;charset=UTF-8"%&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /&gt;
&lt;meta name="layout" content="main" /&gt;
&lt;title&gt;List Cars&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div class="body"&gt;
&lt;table&gt;
&lt;tr&gt;
&lt;th&gt;Car Name&lt;/th&gt;
&lt;th&gt;Car Brand&lt;/th&gt;
&lt;th&gt;Car Production Country&lt;/th&gt;
&lt;th&gt;Car Production Year&lt;/th&gt;
&lt;/tr&gt;
&lt;g:each var="car" in="${cars}"&gt;
&lt;tr&gt;
&lt;td&gt;
${car.carName}
&lt;/td&gt;
&lt;td&gt;
${car.carBrand}
&lt;/td&gt;
&lt;td&gt;
${car.productionCountry}
&lt;/td&gt;
&lt;td&gt;
${car.productionYear}
&lt;/td&gt;
&lt;/tr&gt;
&lt;/g:each&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;g:link controller="registerCar" action="registerAgain"&gt;Register Again&lt;/g:link&gt;
&lt;/body&gt;
&lt;/html&gt;

Here is the detailed explanation for the code above:

  • We’ve used g:each Tag for iterating over the ${cars} binded variable that already returned by the register action.
  • We’ve used the g:link for navigating into registration view again, g:link provides you the ability defining what’s the controller you want to invoke and which the action would you execute. By clicking on the registerAgain link, register view will be shown.

5. Grails MVC Demo

For running the application, follow the below steps:

  • Right click on your project.
  • Select Run As.
  • Select Grails command (run-app).
  • Wait a while until you project started.
  • The link will be listed inside the console. Just click on.

Grails - MVC - Main Page

  • Click on your controller listed above. The controller has provided the default action initialize that will be used in the main page.
  • Initialize action has been executed and it will delegate the control of the application into register view.

Grails - MVC - Register View

  • One action provided for you, Register will invoke the RegisterCarController – register action based on the convention over configuration principle.
  • Register action will has created a new Car and adding it into Cars List.
  • Finally, the view would be selected using the reserved render phrase that’s also populate the needed model that will be used for the next view.

Grails - MVC - List View

  • You have the ability to register another cars by clicking on the Register Again.
  • Register Again action has been developed using the g:link grails component Tag. registerAgain action will be executed that will lead us into the register view again.

6. Summary

MVC architecture is the most often architecure used these days for developing the web applications. This tutorial tend to provide you the full detailed explanation of how could MVC sample be achieved using the Grails Platform. You can contributing us by leaving your comments, questions or suggestions right below.

 

Category: GrailsTag: Grails, Grails GGTS

Previous Post: « Bootstrap Navigation Controls
Next Post: Bootstrap Breadcrumbs »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact