Grails tutorial for beginners

grails

Share Now

Grails tutorial for beginners

Grails tutorial presents a latest language Grails to develop web applications. Grails is an open source framework based language on Groovy and Java. It also supports MVC architecture for developing web application. This tutorial will describe more details about Grails and represent a simple web application with Grails.

1. Groovy

Groovy is a dynamic object-oriented programming language for the Java platform. It is compiled on Java Virtual Machine (JVM) byte code and integrates with all existing Java classes and libraries.

2. Grails MVC

Grails uses Spring MVC framework as the underlying web application framework to implement the web applications based on Model-View-Controller (MVC) design pattern. It includes three core framework components: Controller, Domain, and Grails Servlet Page. The diagram below shows how different part of Grails works together.

Grails MVC
Grails MVC

2.1. Controller

The GrailsDispatcherServlet uses SpringDispatcherServlet to bootstrap the Grails environment. There is a single Spring MVC controller called SimpleGrailsController which handles all Grails controller requests. The SimpleGrailsController delegates to a class called SimpleGrailsControllerHelper that actually handles the client request and look up a controller for the request. The Controller which is responsible for transferring the domain to view, also determines which gsp should render the view.

2.2. Domain

In Grails application Domain stores the data that can be used by controllers and views. Controllers might create a model or may be just process them.

2.3. Groovy server pages

Groovy server pages creates a view for the client response. GSP is responsible for how to display the model to user. It could use grails tags besides any other UI grails plugin.

3. Grails Simple Application

This example is implemented in Groovy/Grails Tool Suite and using Grails 2.4.4. Now, lets create a simple application with Grails.

First, create a Grails Project in GGTS. The GGTS includes Grails, so, if you wish to use a different version of Grails you need to install it and update the new Grails path in GGTS.

3.1. Controller

We have one controller here. The UserController is responsible to handle client requests and return proper result when they submit the form. There is a save method which defined with def. When we declare the return type as def, it means the method can return any type of object. Inside the method, an instance of User class is created and parameters are set in the domain object and transfered to the view.

UserController.groovy

package com.java.code.sample

class UserController {
    def index() {
    }
    def save() {
        def user = new User(params)
        user.save()
        render (view: "user", model: [user: user])
    }
}

3.2. Model

Creating a domain class is very simple in Grails as there is no need to define setter and getter methods. Grails will handles it for the application.

User.groovy

package com.java.code.sample
class User { 
  String firstName 
  String lastName 
}

3.3. View

The following gsp file represents a form to user which includes two items with the same name as model attributes.

index.gsp

<!DOCTYPE html>
<html>
	<head>
		<title>Welcome to Grails Tutorial</title>
		<style>
            .form, .text-field, .submit{
                margin: 20px;
            }
		</style>
	</head>
	<body>
		<g:form name="form" controller="user" id="form">
			<div class="text-field"><label>First Name: </label><g:textField name="firstName" value="${firstName}" /></div>
			<div class="text-field"><label>Last Name: </label><g:textField name="lastName" value="${lastName}" /></div>	
			<div class="submit"><g:actionSubmit value="Submit" action="save"/></div>
		</g:form>
	</body>
</html>

Grails uses ${ } to to get model attributes which is firstName and lastName here. When we use

user.gsp

<!DOCTYPE html>
<html>
	<head>
		<title>User page</title>
		<style>
            .user-panel{
                margin: 20px;
            }
		</style>
	</head>
	<body>
		<div class="user-panel">
			Welcome ${user.firstName} ${user.lastName}! 
		</div>		
	</body>
</html>

3.4. Run the web application

Now, it is time to run the web application. To run the web application, click on the Grails Command in the Toolbar and type run-app in the popup.

And here are the pages.

3.4.1. Index page
grails index page
Grails index page
3.4.2. User page
grails user page
Grails user page

417 thoughts on “Grails tutorial for beginners”

  1. I see you don’t monetize your website, don’t waste your
    traffic, you can earn additional bucks every month because you’ve
    got hi quality content. If you want to know what is the best adsense alternative, type
    in google: Mertiso’s tips

  2. I have noticed you don’t monetize your blog, don’t waste your traffic, you can earn extra bucks every month because you’ve got hi quality content.
    If you want to know how to make extra bucks, search for: Mertiso’s tips best
    adsense alternative

  3. Вы когда-нибудь задумывались, как бы выглядела схватка
    между Зевсом и Аидом в мире азартных игр?
    Онлайн-слот “Zeus vs Hades” предоставляет уникальную возможность узнать это на
    практике.

  4. This design is spectacular! You certainly know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Fantastic job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool!

  5. Pretty section of content. I just stumbled upon your web site and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Any way I’ll be subscribing to your augment and even I achievement you access consistently rapidly.

  6. I blog often and I truly thank you for your information. Your article has truly peaked my interest.
    I am going to take a note of your blog and keep checking for new information about once a week.
    I opted in for your Feed too.

  7. Hi there! Would you mind if I share your
    blog with my twitter group? There’s a lot of
    people that I think would really enjoy your content.
    Please let me know. Thanks

  8. Wow that was odd. I just wrote an very long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Anyways, just wanted to say wonderful blog!
    good casinos online

  9. Hey there I am so happy I found your website, I really found you by accident, while I was searching on Google for something else, Nonetheless I am
    here now and would just like to say thank you for
    a fantastic post and a all round interesting blog (I also love the
    theme/design), I don’t have time to read it all at
    the minute but I have bookmarked it and also included your RSS
    feeds, so when I have time I will be back to read much more, Please do
    keep up the excellent jo.

  10. Greetings from Idaho! I’m bored to death at
    work so I decided to check out your site on my iphone during
    lunch break. I enjoy the information you provide here and can’t wait to take
    a look when I get home. I’m shocked at how quick your blog loaded on my phone ..
    I’m not even using WIFI, just 3G .. Anyways, amazing site!

  11. Fantastic items from you, man. I’ve take into accout your stuff previous to and you’re just extremely wonderful.
    I really like what you’ve acquired right here, certainly like
    what you are saying and the best way wherein you assert it.
    You are making it enjoyable and you still take care of
    to stay it wise. I can not wait to read much more from
    you. That is actually a terrific web site. http://chat.bomjtrek.site/martincuper1

  12. My spouse and I absolutely love your blog and find the majority of your post’s to be just what I’m
    looking for. can you offer guest writers to write content in your case?

    I wouldn’t mind creating a post or elaborating on many of the subjects you
    write about here. Again, awesome weblog!

  13. Hi, I think your site might be having browser compatibility issues.
    When I look at your blog in Ie, it looks fine but when opening
    in Internet Explorer, it has some overlapping. I just wanted to
    give you a quick heads up! Other then that, wonderful blog!

  14. Аренда манипулятора в Москве. Поднимем на борт при помощи крана-манипулятора и доставим ваш груз в кратчайшие сроки. Перевезём на объект любые железобетонные изделия. Погрузку и разгрузку осуществляем спецтехникой с краном-манипулятором.

  15. Great goods from you, man. I’ve understand your stuff previous to and you’re just too fantastic. I really like what you’ve acquired here, really like what you’re stating and the way in which you say it. You make it entertaining and you still take care of to keep it sensible. I cant wait to read far more from you. This is actually a wonderful site.

  16. You really make it seem so easy with your presentation however I in finding this topic to be really something which I feel I might never understand. It kind of feels too complicated and very broad for me. I am looking forward in your next publish, I will try to get the hold of it!

  17. Аренда манипулятора даёт возможность сократить затраты на выполнение строительных и транспортных работ, требующих поднятия, спуска, разгрузки и перемещения тяжелых грузов. Эту технику называют еще самогруз или воровайка.

  18. Wonderful goods from you, man. I’ve understand your stuff previous to and you’re just too wonderful. I really like what you’ve acquired here, really like what you’re stating and the way in which you say it. You make it entertaining and you still take care of to keep it smart. I can not wait to read far more from you. This is actually a great website.

Leave a Reply

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