RSS

Getting started with Grails and Groovy

01 Nov

Grails LogoGrails is a project from SpringSource and VMware led by Graeme RocherGrails, is defined in its website as:

an advanced and innovative open source web application platform that delivers new levels of developer productivity by applying principles like Convention over ConfigurationGrails helps development teams embrace agile methodologies, deliver quality applications in reduced amounts of time, and focus on what really matters: creating high quality, easy to use applications that delight users. Grails naturally complements Java application development since it is built on Spring and based on Groovy, the leading dynamic language for the Java platform.

Grails in a nutshell.

We can say that Grails is a really impressive platorm that allow us to build a web application in a few minutes. It has the same idea behind the scenes, Convention over Configuration, that Maven has. Besides that, Grails uses the well known software pattern MVC. From you domain classes you can build a web application in minutes just generating the other layers (controllers and views) from your POGOs.

Java and Groovy put together.

Groovy Logo

But what is a POGO?. It sounds pretty close to POJO, isn’t it?. POGOs are plain objects, but instead of Java-based are Groovy-based. This is another feature of the Grails platform, Grails gets benefits of Groovy language to speed up the web application development.


Groovy is defined in its website as:

  • is an agile and dynamic language for the Java Virtual Machine
  • builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby and Smalltalk
  • makes modern programming features available to Java developers with almost-zero learning curve
  • supports Domain-Specific Languages and other compact syntax so your code becomes easy to read and maintain
  • makes writing shell and build scripts easy with its powerful processing primitives, OO abilities and an Ant DSL
  • increases developer productivity by reducing scaffolding code when developing web, GUI, database or console applications
  • simplifies testing by supporting unit testing and mocking out-of-the-box
  • seamlessly integrates with all existing Java classes and libraries
  • compiles straight to Java bytecode so you can use it anywhere you can use Java

Great!. As you has read before Groovy can be compiled under the JVM and is completely bytecode compatible. But can you give me a taste of Groovy?. Quite sure, we are going to compare a Java class to a Groovy one.

  • Car.java:
public class Car {
	private String modelo;
	private String marca;
	private long precio;
	private Date inicio;
	public String getModelo() {
		return modelo;
	}
	public void setModelo(String modelo) {
		this.modelo = modelo;
	}
	public String getMarca() {
		return marca;
	}
	public void setMarca(String marca) {
		this.marca = marca;
	}
	public long getPrecio() {
		return precio;
	}
	public void setPrecio(long precio) {
		this.precio = precio;
	}
	public Date getInicio() {
		return inicio;
	}
	public void setInicio(Date inicio) {
		this.inicio = inicio;
	}
  • Car.groovy:
class Car {
	String modelo
	String marca
	long precio
	Date inicio
}
You can notice that with Groovy you don’t need to write every getter and setter in your domain objects. Every Groovy class is public by default, and every attribute is private by default as well. Getters and setters are generated in runtime for the sake of brevity. But there are more, it isn’t required to add a semi-colon at the end of your setences or access modifiers. There are a lot of great Groovy language specifics that are meant to remark as closures, gstrings or safe dereferencing. Another great thing is that you can mix Java and Groovy classes in the same files.
A good book to start with Groovy is Groovy Recipes: Greasing the Wheels of Java by Scott Davis. The first chapter of this book, Groovy, the way Java should be is a great introduction to Groovy. I don’t have a lot of experience with Grails and Groovy, but I think every java developers should spend some time at least playing with these two technologies because they have some cool features. And reading this (or another book) could be a good set-off.

Our first Grails application.

I recommend using STS as your IDE when develop Grails web application. If not, there are a lot of great IDE or text editor that are integrated with Grails, but STS has some nice features to make your develop process quite easy. You don’t need an IDE or a text editor either. You can develop from command line also. If you use STS there is the option to use a Grails console within it.

grails console

To use Grails in our STS instance we need to install it from the Dashboard. Just check Grails support from there and after restart STS you can start with your first Grails app.

Install Grails support from STS dashboard

Next thing you need to do is creat a new Grails project. Select where Grails is installed in your machine and you are ready to start.

new grails project

In your project explorer view you notice that your project has already created with some specified folder inside it. Remenber the Convention over configuration stuff we have previously talked. Here it is🙂. There is a domain, controller or view folder where you have to put your classes depending on their role in your project. I really recommend to read the Grails start guide.

We are going to create a easy domain class. There are class attributes and static constraints that are used to specify how attributes are going to be shown in your future views. In our case the unique constraint is that attributes cannot be blank in our form views.

class Car {
	String modelo
	String marca
	long precio
	Date inicio

	static constraints = {
		marca(blank:false)
		modelo(blank:false)
		precio(blanck:false)
		inicio(blank:false)
	}
}

To generate a simple CRUD controllers and views you can use the generate controller and view command. STS makes it easy and offers us this feature from a option menu.

generate controllers and views

Now you find a DomainClassController and views to create, show or list your domain objects. Obviously you can override and adapt your Groovy controller or GSP pages to your needings. GSP??. Grails uses Groovy server pages to render your web application. It similar to JSP but has his own tags among other features. Besides that Grails uses Sitemesh to design your application layout.

import grails.converters.*

class CarController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [carInstanceList: Car.list(params), carInstanceTotal: Car.count()]
    }

    def create = {
        def carInstance = new Car()
        carInstance.properties = params
        return [carInstance: carInstance]
    }

    def save = {
        def carInstance = new Car(params)
        if (carInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'car.label', default: 'Car'), carInstance.id])}"
            redirect(action: "show", id: carInstance.id)
        }
        else {
            render(view: "create", model: [carInstance: carInstance])
        }
    }

    def show = {
        def carInstance = Car.get(params.id)
        if (!carInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'car.label', default: 'Car'), params.id])}"
            redirect(action: "list")
        }
        else {
            [carInstance: carInstance]
        }
    }

Your view GSP page looks like this.

<%@ page import="firstgrailsapp.Car" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta name="layout" content="main" />
        <g:set var="entityName" value="${message(code: 'car.label', default: 'Car')}" />
        <title><g:message code="default.create.label" args="[entityName]" /></title>
    </head>
    <body>
        <div>
            <span><a href="${createLink(uri: '/')}"><g:message code="default.home.label"/></a></span>
            <span><g:link action="list"><g:message code="default.list.label" args="[entityName]" /></g:link></span>
        </div>
        <div>
            <h1><g:message code="default.create.label" args="[entityName]" /></h1>
            <g:if test="${flash.message}">
            <div>${flash.message}</div>
            </g:if>
            <g:hasErrors bean="${carInstance}">
            <div>
                <g:renderErrors bean="${carInstance}" as="list" />
            </div>
            </g:hasErrors>
            <g:form action="save" >
                <div>
                    <table>
                        <tbody>

                            <tr>
                                <td valign="top">
                                    <label for="marca"><g:message code="car.marca.label" default="Marca" /></label>
                                </td>
                                <td valign="top">
                                    <g:textField name="marca" value="${carInstance?.marca}" />
                                </td>
                            </tr>

                            <tr>
                                <td valign="top">
                                    <label for="modelo"><g:message code="car.modelo.label" default="Modelo" /></label>
                                </td>
                                <td valign="top">
                                    <g:textField name="modelo" value="${carInstance?.modelo}" />
                                </td>
                            </tr>

                            <tr>
                                <td valign="top">
                                    <label for="precio"><g:message code="car.precio.label" default="Precio" /></label>
                                </td>
                                <td valign="top">
                                    <g:textField name="precio" value="${fieldValue(bean: carInstance, field: 'precio')}" />
                                </td>
                            </tr>

                            <tr>
                                <td valign="top">
                                    <label for="inicio"><g:message code="car.inicio.label" default="Inicio" /></label>
                                </td>
                                <td valign="top">
                                    <g:datePicker name="inicio" precision="day" value="${carInstance?.inicio}"  />
                                </td>
                            </tr>

                        </tbody>
                    </table>
                </div>
                <div>
                    <span><g:submitButton name="create" value="${message(code: 'default.button.create.label', default: 'Create')}" /></span>
                </div>
            </g:form>
        </div>
    </body>
</html>

So now, you have a basic Grails web application. Just run it from STS IDE or command line using grails run-app. You can also create a WAR that can be deployed in your prefer web server as Tomcat or JBoss.

welcome to your grails first application

create car view in grails

If you want to add more funcionality Grails makes this really straightforward. You can add some of your Java or Groovy classes to the project. Grails uses Spring and Hibernate (GORM) in their project. You can add more features thanks to Grails plugin. There are lots of them. So what are your waiting for?.

 Grails stuff.

There are not a lot of books about Grails, but those are written are pretty good.

You can join the Grails mail-list too. Looking something else to add in this section I’ve found this post by Tomás Lin that groups a lot of interesting links to Grails material. So, instead of repeating his links I think is a better idea to visit his blog.🙂
If you are living or visiting Madrid , there is a Grails  Groovy and conference this friday named Greach. I will be here, hoping to learn a lot about Grails.
 
1 comentario

Publicado por en 1 noviembre, 2011 en grails, groovy, web

 

Etiquetas: , , ,

Una respuesta a “Getting started with Grails and Groovy

  1. Pingback: JavaPins

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s

 
A %d blogueros les gusta esto: