Jersey - execute 'common' code before running a selected set of subresources

2.3k views Asked by At

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?

2

There are 2 answers

0
gsl On

I use this:

/**
 * This method is called by JAX-RS for each request before the identified resource method is
 * invoked, since it is annotated with the Context annotation.
 */
@Context
public void setServletContext( ServletContext servletContext ) {

}

I put this in the Resource classes.

2
jakubiszon On

In addition to the previous answer, to get the request, response and the session:

@Context
public void setServletContext(
                ServletContext servletContext,
                @Context final HttpServletRequest request,
                @Context final HttpServletResponse response
) {
    // you can also get to the session
    // it is recommended to uncomment the "false" argument below
    // to avoid creating sessions if they don't already exist
    HttpSession session = request.getSession(/*false*/);
}

You can also put this in a class which your resources extend to get it executed for every request in all resources.