Filters

Grails Filters

Since Grails 1.0, Grails supports the concept of filters that can be applied independently of controllers by users or plug-ins. The filters are executed in the order they are defined.

Note on filters and plug-ins:
In the case of plug-ins in the order in which the plug-ins load (please clarify previous sentence). It is therefore important that if you want a filter to be executed after another known filter within another plug-in you must "depend on" that plug-in using the dependsOn attribute. See Plugin Dependencies.

Defining Filters

To create a filter create a class that ends with "Filters" in the grails-app/conf directory. Within this class define a code block called filters that contains the filter definitions:

class MyFilters {
   def filters = {
        // your filters here
   }
}

Each filter you define has a name and a scope. The name is the method name and the scope is defined as named arguments:

myFilter(controller:'*', action:'*') {

}

The scope can be one of the following things:

  • A controller and/or action name pairing with optional wildcards
  • A URI

Some examples:

all(controller:'*', action:'*') {

}
justBook(controller:'book', action:'*') {

}
someURIs(uri:'/book/*') {

}
allURIs(uri:'/*') {

}

Filter Interceptors

Within the body of the filter you can then define one of the following interceptors for the filter:

  • before - Executed before the action. Can return false to indicate all future filters and the action should not execute
  • after - Executed after an action. Takes a first argument as the view model
  • afterView - Executed after view rendering

Some examples

class SecurityFilters {
   def filters = {
       loginCheck(controller:'*', action:'*') {
           before = {
              if(!session.user && !actionName.equals('login')) {
                  redirect(action:'login')
                  return false
               }
           }

       }
   }
}

Filter Dynamic Methods/Properties

Filters support most of the common properties available to controllers and tag libraries including:

  • request - The HttpServletRequest object
  • response - The HttpServletResponse object
  • session - The HttpSession object
  • servletContext - The ServletContext object
  • applicationContext - The ApplicationContext object
  • params - The request parameters object
  • actionName - The action name that is being dispatched to
  • controllerName - The controller name that is being dispatched to

In addition filters support the following methods:

Labels

 
(None)