spring-boot uses Interceptor

1. Inherit HandlerInterceptorAdapter to implement a custom interceptor
2. Rewrite the preHandle method to execute before the request occurs
3. Rewrite the postHandle method to execute after the request is completed
	public class MyMvcInterceptor extends HandlerInterceptorAdapter{

		@Override
		public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
			long startTime = System.currentTimeMillis();
			request.setAttribute("startTime",startTime);
			return true;
		}

		@Override
		public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
			long startTime = (long)request.getAttribute("startTime");
			long endTime = System.currentTimeMillis();
			System.out.println("The request time is: "+(endTime - startTime) + " ms");
			super.postHandle(request, response, handler, modelAndView);
		}
	}



Configure the interceptor bean
to override the addInterceptors method and register the interceptor
	@SpringBootApplication
	@EnableAsync
	public class DemoApplication extends WebMvcConfigurerAdapter{
		@Bean
		public MyMvcInterceptor myMvcInterceptor(){
			return new MyMvcInterceptor();
		}

		@Override
		public void addInterceptors(InterceptorRegistry registry) {
			registry.addInterceptor(myMvcInterceptor());
		}

		public static void main(String[] args)
		{
			SpringApplication.run(DemoApplication.class, args);
		}
	}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326391988&siteId=291194637