Saturday, June 16, 2018

Grails on Groovy > Grails 2.X > How is the invocation sequence of Grails filters defined | Sequence of Filter Execution

I am using filters to handle authentication and some other pre-condition checks for a Grails application. I've run into a situation where it'd be nice to ensure that filter A is always invoked before filter B
If several filters are declared within one class, it's obvious that they'll be executed in the order that they were declared like below code block.
package com.pkm

class SecurityFilters {

    def filters = {
        filter1(controller:'*', action:'*') {
            before = {
                println("FILTER-1")
            }
            after = { Map model ->

            }
            afterView = { Exception e ->

            }
        }

        filter2(uri: "/**") {
            before = {
                println("FILTER-2")
            }
            after = { Map model ->

            }
            afterView = { Exception e ->

            }
        }
    }
}
Now what will happen if they would defined in different classes. Yes, there is a way around and that is dependsOn. You can define dependsOn on which filter it will depend on. Say I created another filter named Security2Filters and set my first filter named SecurityFilters to dependsOn. So SecirutyFilters will be execute before Security2Filters.
package com.pkm

class Security2Filters {
    def dependsOn=[SecurityFilters]

    def filters = {
        all(controller:'*', action:'*') {
            before = {
                println("FILTER-3")
            }
            after = { Map model ->

            }
            afterView = { Exception e ->

            }
        }
    }
}

No comments:

Post a Comment