Nestor Milyaev Nestor Milyaev - 3 months ago 10
Java Question

Java JAX-RS react on ANY endpoint invocation

I have a class implementing a JAX-RS endpoint, as per below:

@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED})
@Path("/site/")
public class ApiSiteResource extends AbstractContentResource {
...
@GET
@Path("/article/")
public Map<String, Object> getArticle (@Context HttpServletRequest request, @Context HttpServletResponse reponse, @BeanParam ApiParams params) {
//do stuff
}

@GET
@Path("/category/")
public Map<String, Object> getCategory (@Context HttpServletRequest request, @Context HttpServletResponse reponse, @BeanParam ApiParams params) {
//do stuff
}


What I need is to perform common processing (for example, capture analytics data) when any of the endponts of the above REST class is invoked, e.g., both for /site/article/ and /site/category/. I'm ideally looking for a solution that would be invoked at the end of the method execution, and ideally with least possible change to the existing methods code, so adding another method call at the end of the method is not the best option as that leads to too much code coupling. Ideally, I would like processing to be fired from an external class.

Is there a way how that could be done?

gsl gsl
Answer

I am using a method of the Resource class that is annotated with the @Context Annotation and has a parameter that is injected from the context scope.

  /**
   * 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 and carries a 
   * context-scope parameter which is injected.
   */
  @Context
  public void setServletContext( ServletContext servletContext ) {
     ...
  }

(If you remove the ServletContext parameter, the automatic invocation on each resource call vanishes - at least in Jersey.) Furthermore, you can put this method in a base class, say DefaultResourceImpl, which your Resource classes can extend, so you have this for all your Resource classes.