Filters - AlexGPlay/Blynder GitHub Wiki

Filters are a bean that serves the function of filtering some requests that are sent to certain controllers.

How to use

A filter is also a bean, so the first step is to create a filter class and add the annotation, in this case is @Filter.

@Filter
public class FooFilter{
...
}

Well, now we have a filter, but, how does it work? That's easy, you just have to create methods inside it and request the parameters that you would usually request in a controller. Let's give it try.

@Filter
public class FooFilter{

	public void filterFooRequests(Response res, Request request){
	...
	}

}

Now we have our method, so the requests that are given to a ceratin controller will need to pass what we say inside here, now two questiosn will arive. What controllers? We will se that in a moment. What conditions? We will se this now. In order to make the filter the one who decides whether a request can continue to the controller or not we have two properties in the Response class, canContinue and redirect. CanContinue is false if your conditions aren't fulfilled and redirect is set to where you want the request to go. Lets see an example.

@Filter
public class FooFilter{

	public void filterFooRequests(Response res, Request request){
		...
		res.canContinue(false).redirect("/");
	}

}

In this example, given some conditions that we can set the user will be redirected to the main page. And what if you want the user to continue? You can set the canContinue to true. Now let's see a more complete filter, imagine that we have a User class and it has a kind, like normal and admin users, now let's imagine that the user wants to access the admin page, if the user is not admin we can't allow that, lets go with that.

@Filter
public class FooFilter{

	public void filterFooRequests(Response res, Request request){
		User user = (User)Application.get("user");
		
		if(user.kind().equals("admin");
			res.canContinue(true);
		else
			res.canContinue(false).redirect("/");
	}

}

There you have it, a filter that can protect the admin pages. Now, the next question, how do we use it in the controllers we want? That is an easy question. You can do it with the @FilterWith annotation, you have to set it to the controller you want to filter.

@FilterWith
@Controller
public class FooController{
...
}

Now that we have this, we can set the filters in two ways, we can specify the class name as string or as Class, given that a controller can be filtered with multiple filters, the parameters to this annotation are arrays. The two methods that we can use inside the annotation are filtersAsClasses and filtersAsString, we will put one class in each of them.

@FilterWith(filterAsClasses={FooFilter1.class}, filterAsString={"FooFilter2"})
@Controller
public class FooController{
...
}

There you have it, this controller methods will be filtered with the FooFilter1 and FooFilter2.