Nestor Milyaev Nestor Milyaev - 2 years ago 141
Java Question

Java JAX-RS react on ANY endpoint invocation

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

public class ApiSiteResource extends AbstractContentResource {
public Map<String, Object> getArticle (@Context HttpServletRequest request, @Context HttpServletResponse reponse, @BeanParam ApiParams params) {
//do stuff

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 Source

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.
  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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download