Thursday, October 8, 2015

Jersey2 Request Filters

What and Why?

Jersey filter is an interceptor class (mediator) we use to filter the requests before hitting out the end point.
(Caller)  --> Filter  --> (End point)

Eg:
We can check the Authorization functionality here.
Lets assume we have an end point which returns user permission details.
So if we need to filter only the requests come through a particular client, we can add a filter and allow only the valid requests.

Implementation


import javax.ws.rs.container.ContainerRequestFilter;

public class AuthorizationFilter implements ContainerRequestFilter { 
    @Override public void filter(ContainerRequestContext request) throws IOException {
        
            if (!isAuthorized()) {
               // Throw Exception here
            }
        }
    }

    private Boolean isAuthorized() {
        boolean isAuthorized = true;

        //implement the logic here.
        return isAuthorized;
    }
}

No comments:

Post a Comment