Grails MVC Tutorial

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:

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 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<Car> carList = new ArrayList<Car>();
	// 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

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

  	</g:form>
  </div>
</body>
</html>

Some important tips should be mentioned here:

  • Grails provide you the 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

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

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.

 

Comments

comments

Speak Your Mind

*