CodeToLive

Grails Framework

Grails is a powerful web application framework built on Groovy that leverages Spring Boot, Hibernate, and other Java technologies while providing a highly productive environment.

Key Features

  • Convention-over-configuration approach
  • Seamless integration with Java ecosystem
  • GORM (Grails Object Relational Mapping)
  • Built-in development tools and plugins
  • RESTful and reactive support

Creating a Grails Application

# Install Grails (requires Java)
sdk install grails

# Create new application
grails create-app myapp

# Run application
cd myapp
grails run-app

Grails Architecture

Grails follows the MVC (Model-View-Controller) pattern:

grails-app/
    controllers/   # Controllers handle requests
    domain/        # Domain classes (entities)
    services/      # Business logic
    views/         # GSP (Groovy Server Pages)
    conf/          # Configuration
    assets/        # Static resources

Domain Classes (GORM)

Grails uses GORM for database access, which provides a simple interface to Hibernate:

// grails-app/domain/com/example/Book.groovy
package com.example

class Book {
    String title
    String author
    Date releaseDate
    BigDecimal price
    
    static constraints = {
        title blank: false
        author blank: false
        releaseDate nullable: true
        price min: 0.0
    }
}

Controllers

Controllers handle HTTP requests and return responses:

// grails-app/controllers/com/example/BookController.groovy
package com.example

class BookController {
    
    def index() {
        [books: Book.list()]
    }
    
    def show(Long id) {
        [book: Book.get(id)]
    }
    
    def save(Book book) {
        if (book.save()) {
            redirect action: "show", id: book.id
        } else {
            render view: "create", model: [book: book]
        }
    }
}

Views (GSP)

Groovy Server Pages (GSP) is the default templating engine:

<%-- grails-app/views/book/index.gsp --%>
<!DOCTYPE html>
<html>
<head>
    <title>Books</title>
</head>
<body>
    <h1>Book List</h1>
    <ul>
        <g:each in="${books}" var="book">
            <li>${book.title} by ${book.author}</li>
        </g:each>
    </ul>
</body>
</html>

Grails Plugins

Grails has a rich plugin ecosystem:

# Install a plugin (e.g., Spring Security)
grails install-plugin spring-security-core
← Back to Tutorials