SpringBoot——拦截器(八)

简介

Springboot 中的 Interceptor 拦截器也就是 mvc 中的拦截器,只是省去了 xml 配置部分。

自定义拦截器

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
40
41
42
43
44
45
46
47
48
49
50
51
package com.qn.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LogHandlerInterceptor implements HandlerInterceptor {
Logger logger = LoggerFactory.getLogger(LogHandlerInterceptor.class);
/**
* 请求方法执行之前
* 返回true则通过
*
* @param request
* @param response
* @param handler
* @return
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
StringBuffer requestURL = request.getRequestURL();
logger.info("preHandle请求URL:" + requestURL.toString());
return true;
}

/**
* 返回modelAndView之前执行
* @param request
* @param response
* @param handler
* @param modelAndView
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
logger.info("postHandle返回modelAndView之前");
}

/**
* 执行Handler完成执行此方法
* @param request
* @param response
* @param handler
* @param ex
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
logger.info("afterCompletion执行完请求方法完全返回之后");
}
}

注册

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
package com.qn.config;

import com.qn.interceptor.LogHandlerInterceptor;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@SpringBootConfiguration
public class MvcWebConfig extends WebMvcConfigurationSupport {

/**
* 添加自定义拦截器
* .addPathPatterns("/**") 拦截的请求路径
* .excludePathPatterns("/user"); 排除的请求路径
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LogHandlerInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/user");
}

}

测试

启动,访问:

SpringBoot——拦截器(八)_2020-05-19-09-47-28.png

|