Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails Filters vs Interceptor

Tags:

grails

I have been studying Grails for quite a while now. And scanned a little bit about Filters and Interceptors. Both have almost the same functionality of tracking the sessions or redirecting unauthorized users in a particular controller.

But I'm confused when and why should I use Filter than Interceptor and vice versa. Given that the Inceptors have two controller methods beforeInterceptor and afterInterceptor and for the Filters a three common closures before, after and afterView.

My questions is what are the pros and cons of using Filter against Interceptor or vise versa. In this manner we, developers, can decide when, where, and why we should use either Filter or Interceptor in a particular Controller to do some tracking, redirect, etc.

like image 509
David B Avatar asked Jul 26 '12 02:07

David B


2 Answers

Use one or both interceptors in a controller when the interception logic only applies to that controller.

Use a filter when the logic applies to multiple (or all) controllers, or when you need to do something after the view is rendered (there's no interceptor equivalent of afterView), or if you just want to keep everything centralized in one place instead of spread across separate controller files.

like image 140
Burt Beckwith Avatar answered Oct 18 '22 01:10

Burt Beckwith


The Old Filters (From Grails 2) are deprecated in Grails 3. The replacement to the Filters are Interceptors.

The use of interceptors is for actions such as: authentication, loggin, etc.
The interceptors (as their name implies) are intercepting the incoming web requests and trigger a related actions. The actions are defined in the related Controller.

The Interceptors have some major benefits (over the Filters) such as support for static compilation, and enable flexible configurations.
These are the main 3 methods of the Interceptor:
- boolean before() { true }
- boolean after() { true }
- void afterView() { }

The Iterceptors are configured as Spring Beans (in the Spring application context) and are configured to be auto-wired by their names.

like image 21
Rotem Avatar answered Oct 18 '22 02:10

Rotem