(Quick Reference)

beforeInterceptor

Purpose

Allows the interception of an action before it is executed. A beforeInterceptor can optionally halt execution of the action all together.

Examples

Simply tracing interceptor:

def beforeInterceptor = {
       println "Tracing action ${actionUri}"
}

A security interceptor to implement login functionality:

def beforeInterceptor = [action:this.&auth,except:'login']
// defined as a regular method so its private
def auth() {
     if(!session.user) {
            redirect(action:'login')
            return false
     }
}
def login = {
     // display login page
}

Description

The beforeInterceptor intercepts processing before the action is executed. If it returns false then the action will not be executed. The interceptor can be defined for all actions in a controller as follows:

def beforeInterceptor = {
       println "Tracing action ${actionUri}"
}

The above is declared inside the body of the controller definition. It will be executed before all actions and does not interfere with processing. A common use case is however for authentication:

def beforeInterceptor = [action:this.&auth,except:'login']
// defined as a regular method so its private
def auth() {
     if(!session.user) {
            redirect(action:'login')
            return false
     }
}
def login = {
     // display login page
}

The above code defines a method called 'auth'. A method is used so that it is not exposed as an action to the outside world (i.e. it is private). The 'beforeInterceptor' then defines an interceptor that is used on all actions 'except' the login action and is told to execute the 'auth' method. The 'auth' method is referenced using Groovy's method pointer syntax, within the method itself it detects whether there is a user in the session otherwise it redirects to the login action and returns false, instruction the intercepted action not to be processed.