Skip to content
German Escobar edited this page Aug 2, 2014 · 10 revisions

An interceptor, as its name implies, provides a mechanism to "intercept" HTTP requests (i.e. for authentication, response compression, logging, etc.). This guide you will show you how to create and configure interceptors in Jogger.

Creating a interceptor

A interceptor is a class that implements org.jogger.interceptor.Interceptor as in the following example:

public class MyInterceptor implements Interceptor {

    @Override
    public void intercept(Request request, Response response, InterceptorExecution execution) throws Exception {
        execution.proceed();
    }

}

Although this interceptor is doing basically nothing, it shows the basics of an interceptor. The most important part is the call to execution.proceed() which will continue with the execution call. If you want to stop the request, just omit that line.

Adding interceptors to your application

You can add interceptors to your RouterMiddleware like this:

    RouterMiddleware router = new RouterMiddleware();
    router.addInterceptor( new MyFirstInterceptor() ); // this will match all the requests
    router.addInterceptor( new MySecondInterceptor(), "/login", "/register" ); 

Retrieving Controller and Action info

You can retrieve information from the Controller or the Action you are intercepting using the org.jogger.interceptor.InterceptorExecution object that you receive as a parameter of your interceptors. For example, you can check if the Controller or Action contains a specific Annotation. For example:

public class SecurityInterceptor implements Interceptor {

    @Override
    public void intercept(Request request, Response response, InterceptorExecution execution) throws Exception {
        Controller controller = execution.getController();
        Action action = execution.getController();
        if (controller.getAnnotation(Secured.class) != null || action.getAnnotation(Secured.class) != null) {
            // check authentication info and decide if it proceeds
        } else {
            execution.proceed();
        }
    }

}