Filter
What is a filter?
Filters are methods that executed before or after a controller action.
By using ActionControl class, a controller can specify either before or after filters for its action methods. There are also skipBeforeFilter and skipAfterFilter methods.
Filters are declared in a controller class's static block.
Examples of using filters:public class PostsControl { static { filterManagerFor(PostsControl.class).declareBeforeFilter( AccountController.class, "loginRequired", "except", "index, show"); filterManagerFor(PostsControl.class).declareBeforeFilter( AccountController.class, "checkModeratorRole", "only", "delete, edit, update"); } ... }
"only" and "except" are the two options you can specify when declaring filters.
In the above example, checkModeratorRole and loginRequired are two methods of the AccountController class as follows.
public class AccountController extends ActionControl { //checks if the user has moderator role public String checkModeratorRole() { return checkRole("Moderator"); } //checks if the user has a specific role private String checkRole(String role) { boolean check = false; if (isLoggedIn()) { User user = getLoggedInUser(); if (user != null && user.hasRole(role)) { check = true; } } if (!check) { flash("error", "You do not have the permission to do that."); return "redirectTo=>/signon/login"; } return null; } public static String loginRequired() { if (!isLoggedIn()) { flash("error", "You must be logged in to do that."); return "redirectTo=>/signon/login"; } return null; } ... }
When a "delete post" request comes in, the "loginRequired" before filter will be invoked, as only "index" and "show" actions can bypass the fitler. If the user already logs in, the request would pass the "loginRequired" filter successfully. Then the next filter "checkModeratorRole" will be invoked. If the user does not have a moderator role, then
Writing a filter method
As you can see from the above example, writing a filter method is like writing an action method. It must be a public method with no parameter input and returns a null value for success case. If anything failed in the filter method, it must return a special tagged String to tell the processor what to do next.
Registering a filter
To register a filter for a controller, you must use the filterManagerFor method. See the above example on using filters.