I have a Java Web application which uses Jersey to expose a REST API.
@Path("/myRootResource")
public class resource
{
@GET
@Path("subResource_1")
public Response subResource_1() {return null;}
@GET
@Path("subResource_2")
public Response subResource_2() {return null;}
}
I want to run some code for every subresource under a specific resource. This code handles authentication tasks, performance metrics (e.g start time to calculate the request's time) initialization and debugging variables.
Until now I have all my code in a function (e.g. preTasks()
), which I run in the beginning of each sub-resource method. I need to some how automate this and make that code-block to run for every sub resource of myRootResource
, without having to copy-paste the aforementioned function to every sub-resource method.
Is this something that can be done with Jersey's Filters or Interceptors?
While I am not really familiar with Spring, I think that what I am trying to achieve is somehow similar to this: Spring web application: executing common code before entering RequestMapping in controller
Update 12/06/2015
As pointed in the comments, 'Interceptors' is a good way to go. But 'Interceptors' are supported only from Jersey 2.X and above. In my code I am using Jersey 1.18. Upgrading to Jersey 2.X breaks some part of my code, so I am trying to avoid this at the moment.
Is there any equivalent to 'Interceptors' in Jersey 1.18, or my only option is the upgrade. I think 'Dispatchers' may to the job, is this correct?
I use this:
I put this in the Resource classes.