Hi everyone, in this post I just want to share simple sticky code on How to capture every single URL which requested in Spring. Okay lets rolling the ball.
Add Log4j maven dependency on your pom.xml
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.8</version> </dependency>
We will capture all URL requested by using Interceptor, so the first step you should make a class which is extend from org.springframework.web.servlet.handler.HandlerInterceptorAdapter, lets see below :
package com.estartup.sys.util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class SysLogInterceptor extends HandlerInterceptorAdapter {
private final Logger log = Logger.getLogger(getClass());
/**
* This implementation always returns {@code true}.
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
log.info("eStartup - "+request.getRequestURI()+" - Entering ... ");
return true;
}
/**
* This implementation is empty.
*/
@Override
public void postHandle(
HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
}
/**
* This implementation is empty.
*/
@Override
public void afterCompletion(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
log.info("eStartup - "+request.getRequestURI()+" - Exiting ... ");
}
}
as you can see in this class you will override 3 methods preHandle, postHandle, and afterCompletion.
And the second step is go to your Application Config (in this post I am using Spring Java Configuration) and register your custom interceptor.
@Configuration
@EnableWebMvc
@PropertySource("classpath:/config/mapping-controllers.properties")
@ComponentScan(basePackages = "com.estartup")
public class AppConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
SysLogInterceptor logInterceptor = new SysLogInterceptor();
registry.addInterceptor(logInterceptor);
}
}
Start your server and the result is :
Okt 08, 2016 8:00:26 PM org.apache.catalina.startup.Catalina start INFO: Server startup in 8457 ms [20:00:31] INFO com.estartup.sys.util.SysLogInterceptor:20 - eStartup - /estartup/welcome - Entering ... [20:00:31] INFO com.estartup.sys.util.SysLogInterceptor:41 - eStartup - /estartup/welcome - Exiting ...
Good Luck