johnmills johnmills - 5 years ago 138
Java Question

Audit/Log all incoming web requests to @RequestMapping annotated methods

Source

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-handlermapping

I have Controller classes annotated with @Controller, they have methods annotated with @RequestMapping. My task is to audit all the web requests received by the Controller classes to @RequestMapping methods, I am using datatables on UI to send and receive response from controllers. the Audit framework is already in place.

The project is configured in Java Config.

I am not sure how to proceed on getting this done.

// Configure Interceptor

public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor());
}

public @Bean
RequestMappingHandlerMapping requestMappingHandlerMapping() {
RequestMappingHandlerMapping handlerMapping = new RequestMappingHandlerMapping();
handlerMapping.setAlwaysUseFullPath(true);
handlerMapping.setUseSuffixPatternMatch(false);
return handlerMapping;
}
}

//Add Handler
@Component
public class MyInterceptor extends HandlerInterceptorAdapter {
@Inject RequestMappingHandlerMapping requestMappingHandlerMapping;
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// do stuff - ( Does my Audit Code go here? eg: Logger.info("xyz request"))
return true;
}
}


I was thinking something like this would work.

Any Suggestions on this, and
if its easier Using Listener or some other Interceptor, it would be helpful

Answer Source

Using interceptors you have full access to the HandlerMethod which provides convenient access to method parameters, the method return value, method annotations, etc.

The following example intercepts and logs mapped requests.

class WebMvcConfig extends WebMvcConfigurerAdapter {

   @Override
   public void addInterceptors(InterceptorRegistry registry) {
      registry.addInterceptor(new HandlerInterceptorAdapter() {
         Logger logger = LoggerFactory.getLogger(WebMvcConfig.class);

         @Override
         public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            if (handler instanceof HandlerMethod) {
               HandlerMethod handlerMethod = (HandlerMethod) handler;
               Method method = handlerMethod.getMethod();
               logger.info("{} - {} - method '{}' on controller '{}'",
                     request.getMethod(), request.getRequestURI(), method.getName(),
                     handlerMethod.getBean().getClass()
               );
            }
            return true;
         }
      });
   }
}

It returns true to continue with the execution chain (and forward the request to other interceptors or the controller-method itself).

An example log-output looks like:

GET - /greeting - method 'greeting' on controller 'class hello.GreetingController'

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