Spring之拦截器

全栈开发私房菜

共 5548字,需浏览 12分钟

 ·

2021-07-29 09:36

一、SpringMvc拦截器

springmvc.xml配置

<mvc:interceptors>
<
mvc:interceptor>
<
mvc:mapping path="/**" />
<bean
class="com.test.interceptor.MyInterceptor">
</bean>
</
mvc:interceptor>
</
mvc:interceptors>


拦截器MyInterceptor类代码(统计接口访问次数)

public class MyInterceptor extends HandlerInterceptorAdapter {


private
ThreadLocal<StopWatch> stopWatchLocal = new ThreadLocal<StopWatch>();

@Autowired
protected SystemInterfaceLogService systemInterfaceLogService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
StopWatch stopWatch = new StopWatch(handler.toString());
stopWatchLocal.set(stopWatch);
stopWatch.start("stopWatchLocal");
return super.preHandle(request, response, handler);
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
Long time = 0L;
StopWatch stopWatch = stopWatchLocal.get();
if
(stopWatch != null) {
if (stopWatch.isRunning()) {
stopWatch.stop();
time = stopWatch.getTotalTimeMillis();
stopWatchLocal.remove();
}
}
String currentPath = request.getRequestURI();
String requestType = request.getMethod();
String queryString = "";
if
(requestType.equals("GET")){
queryString = request.getQueryString();
queryString = queryString == null ? "" : "?" + queryString;
}else{
BufferedReader br=request.getReader();
String inputLine = "";
while ((inputLine = br.readLine()) != null) {
queryString += inputLine;
}
br.close();
}
SystemInterfaceLogDtl data = new SystemInterfaceLogDtl();
data.setUrlId(UUID.randomUUID().toString());
data.setSystemType("test");
      data.setRequestUrlName(currentPath.substring(currentPath.lastIndexOf("/")+1,currentPath.length()));     
      //请求接口路径

data.setRequestUrl(currentPath);

      //请求接口参数

data.setRequeryParm(queryString);

      //请求接口时长(ms)
data.setRequeryTime(time);
String date = DateUtils.convertToTime(new Date());
data.setCreateTime(date);
data.setLastTime(date);
systemInterfaceLogService.insertSystemInterfaceLog(data);
super
.afterCompletion(request, response, handler, ex);

}


@Override
public void afterPropertiesSet() throws Exception {

}
}


二、SpringBoot拦截器

添加web过滤器

1、添加web 过滤器,管理过滤的类,以及过滤的请求路径

2、实现WebMvcConfigurer 类,复写父类的方法 addInterceptors

3、通过registry.addInterceptor拦截类,addPathPatterns拦截路径,excludePathPatterns添加允许路径


@Configuration
public class addInterceptor implements WebMvcConfigurer {
@Resource
private MyInterceptor authInterceptor;
/**
* 自定义资源映射
*
*
@param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {

}

/**
* 拦截页面
*
*
@param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor).addPathPatterns("/**").excludePathPatterns("/");
}

/**
* 视图跳转控制器
*
@param registry
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {

}

/**
* 默认静态资源处理器
*
@param configurer
*/
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {

}

/**
* 配置视图解析器
*
@param registry
*/
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
}

/**
* 配置内容裁决的一些选项
*
@param configurer
*/
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {

}
}


拦截器MyInterceptor类代码(统计接口访问次数)

@Component
public class MyInterceptor extendsHandlerInterceptorAdapter {

private ThreadLocal<StopWatch> stopWatchLocal = new ThreadLocal<StopWatch>();
@Autowired
protected SystemInterfaceLogService systemInterfaceLogService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
StopWatch stopWatch = new StopWatch(handler.toString());
stopWatchLocal.set(stopWatch);
stopWatch.start("stopWatchLocal");
return super.preHandle(request, response, handler);
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
Long time = 0L;
StopWatch stopWatch = stopWatchLocal.get();
if
(stopWatch != null) {
if (stopWatch.isRunning()) {
stopWatch.stop();
time = stopWatch.getTotalTimeMillis();
stopWatchLocal.remove();
}
}
String currentPath = request.getRequestURI();
String requestType = request.getMethod();
String queryString = "";
if
(requestType.equals("GET")){
queryString = request.getQueryString();
queryString = queryString == null ? "" : "?" + queryString;
}else{
BufferedReader br=request.getReader();
String inputLine = "";
while ((inputLine = br.readLine()) != null) {
queryString += inputLine;
}
br.close();
}
SystemInterfaceLogDtl data = new SystemInterfaceLogDtl();
data.setUrlId(UUID.randomUUID().toString());
data.setSystemType("test");
      data.setRequestUrlName(currentPath.substring(currentPath.lastIndexOf("/")+1,currentPath.length()));     
      //请求接口路径

data.setRequestUrl(currentPath);

      //请求接口参数

data.setRequeryParm(queryString);

      //请求接口时长(ms)
data.setRequeryTime(time);
String date = DateUtils.convertToTime(new Date());
data.setCreateTime(date);
data.setLastTime(date);
systemInterfaceLogService.insertSystemInterfaceLog(data);
super
.afterCompletion(request, response, handler, ex);

}


@Override
public void afterPropertiesSet() throws Exception {

}


浏览 24
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报