8.5.1 Defining Interceptors

By default interceptors will match the controllers with the same name. For example if you have an interceptor called BookInterceptor then all requests to the actions of the BookController will trigger the interceptor.

An Interceptor implements the Interceptor trait and provides 3 methods that can be used to intercept requests:

  1. /**
  2. * Executed before a matched action
  3. *
  4. * @return Whether the action should continue and execute
  5. */
  6. boolean before() { true }
  7. /**
  8. * Executed after the action executes but prior to view rendering
  9. *
  10. * @return True if view rendering should continue, false otherwise
  11. */
  12. boolean after() { true }
  13. /**
  14. * Executed after view rendering completes
  15. */
  16. void afterView() {}

As described above the before method is executed prior to an action and can cancel the execution of the action by returning false.

The after method is executed after an action executes and can halt view rendering if it returns false. The after method can also modify the view or model using the view and model properties respectively:

  1. boolean after() {
  2. model.foo = "bar" // add a new model attribute called 'foo'
  3. view = 'alternate' // render a different view called 'alternate'
  4. true
  5. }

The afterView method is executed after view rendering completes. If an exception occurs, the exception is available using the throwable property of the Interceptor trait.