0%

SpringBoot使用HandlerInterceptor拦截器

编写一个拦截器,实现HandlerInterceptor接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* TimerInterceptor
*
* @author jlin
* @date 2019-05-30 09:19
* @Description
*/
@Component
@Slf4j
public class TimerInterceptor implements HandlerInterceptor {
/**
* This implementation always returns {@code true}.
*
* @param request
* @param response
* @param handler
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.debug("收到请求-->{}", request.getRequestURI());
request.setAttribute("startTime", System.currentTimeMillis());
return true;
}

/**
* 控制器方法抛不抛异常都会被调用
*
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
Long startTime = (Long) request.getAttribute("startTime");
log.debug("请求耗时-->url:{}-->time:{},", request.getRequestURI(), (System.currentTimeMillis() - startTime));
}
}

编写一个类,继承WebMvcConfigurerAdapter抽象类,将其放入Spring容器中,然后重写addInterceptors()方法,并调用给的参数InterceptorRegistry.addInterceptor()把自己编写的那个拦截器作为参数加进去。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* WebConfig
*
* @author jlin
* @date 2019-05-29 16:12
* @Description
*/
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Autowired
private TimerInterceptor timerInterceptor;

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