拦截请求并记录相应信息-springboot
方式:
1、FIlter过滤器
2、interceptor拦截器
3、Aspect切片
一、Filter过滤器形式
只能处理request中的数据 不能确定请求要走的是哪个controller信息
1、过滤器实现第一种方式
package com.nxz.filter; import org.springframework.stereotype.Component; import javax.servlet.*;
import java.io.IOException;
import java.util.Date; // Filter 是javax.servlet下的
@Component //让自定义filter起作用,只需要让springcontext管理起来即可
public class TimeFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("time filter init");
} @Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("time filter start");
long time = new Date().getTime();
filterChain.doFilter(servletRequest, servletResponse);
System.out.println("消耗时间:" + (new Date().getTime() - time));
System.out.println("time filter start");
} @Override
public void destroy() {
System.out.println("time filter destroy");
}
}
当项目启动的时候会在控制台输出:time filter init
当访问localhost:8080/user/1时:进入拦截器

结束结束后:
time filter start
进入getinfo服务
消耗时间:
time filter end
2、filter过滤器第二种方式
package com.nxz.filter; import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class WebConfig { @Bean
public FilterRegistrationBean timeFilter(){ FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); TimeFilter timeFilter = new TimeFilter();
filterRegistrationBean.setFilter(timeFilter); //指定什么样的请求回走timefilter过滤器
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
}
}
二、inteceptor拦截器
只能处理到类中的方法,但是不能记录方法的参数是什么
package com.nxz.inteceptor; import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date; @Component
public class TimeInteceptor implements HandlerInterceptor { //在controller调用之前调用
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.out.println("preHandler"); System.out.println(((HandlerMethod) o).getBean().getClass().getName());//输出类名
System.out.println(((HandlerMethod) o).getMethod().getName());//输出方法名 //为了在prehandler方法和posthandler方法之间传递信息,可以将数据放到request中
httpServletRequest.setAttribute("startTime", new Date().getTime());
return false;
} //在controller调用之后调用,如果controller中抛出异常,这个方法不会调用
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
Long start = (Long) httpServletRequest.getAttribute("startTime");
System.out.println("time interceptor 耗时:" + (new Date().getTime() - start));
} //无论controller是否抛出异常,都会调用
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("afterCompletion");
Long start = (Long) httpServletRequest.getAttribute("startTime");
System.out.println("time interceptor 耗时:" + (new Date().getTime() - start));
System.out.println("ex is :" + e);
}
}
interceptor实现拦截功能还需要配置webconfig
package com.nxz.config; import com.nxz.filter.TimeFilter;
import com.nxz.inteceptor.TimeInteceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration
public class WebConfig extends WebMvcConfigurerAdapter { @Autowired
private TimeInteceptor timeInteceptor;
//自定义的interceptor 要起作用的话 需要继承webmvcConfigurerAdater ,重写addInterceptors
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(timeInteceptor);
}
}
访问localhost:8080/user/1后,输入日志:
preHandler
com.nxz.controller.UserController
getInfo
进入getinfo服务
postHandle
time interceptor 耗时:
afterCompletion
time interceptor 耗时:
ex is :null
三、切片Aspect(AOP) -- 切入点(注解)、增强(方法)
需要导入aop依赖
package com.nxz.aspect; import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component; import java.util.Date; @Aspect
@Component
public class TimeAspect { //@Before @After @AfterThrowing @Around 基本的aop注解 @Around("execution(* com.nxz.controller.UserController.*(..))")
public Object handlerControllerMehtod(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("time aspect start"); Object[] args = joinPoint.getArgs();
for (Object arg : args) {
System.out.println(arg);
} Long time = new Date().getTime();
Object obj = joinPoint.proceed(); System.out.println("time aspect end,耗时:" + (new Date().getTime() - time)); return obj;
} }
访问地址后:
time aspect start
1 --》请求参数
进入getinfo服务
time aspect end,耗时:
几种方式起作用的顺序:

====
Usercontroller:
@GetMapping("/{id:\\d+}")
@JsonView(User.UserDetailView.class)
public User getInfo(@PathVariable String id) {
System.out.println("进入getinfo服务");
User user = new User();
user.setUsername("tom");
return user;
}
拦截请求并记录相应信息-springboot的更多相关文章
- Springboot通过拦截器拦截请求信息收集到日志
1.需求 最近在工作中遇到的一个需求,将请求中的客户端类型.操作系统类型.ip.port.请求方式.URI以及请求参数值收集到日志中,网上找资料说用拦截器拦截所有请求然后收集信息,于是就开始了操作: ...
- spring Boot使用AOP统一处理Web请求日志记录
1.使用spring boot实现一个拦截器 1.引入依赖: <dependency> <groupId>org.springframework.boot</grou ...
- .net core MVC 通过 Filters 过滤器拦截请求及响应内容
前提: 需要nuget Microsoft.Extensions.Logging.Log4Net.AspNetCore 2.2.6: Swashbuckle.AspNetCore 我暂时用的是 ...
- asp.net core 使用中间件拦截请求和返回数据,并对数据进行加密解密。
原文:asp.net core 使用中间件拦截请求和返回数据,并对数据进行加密解密. GitHub demo https://github.com/zhanglilong23/Asp.NetCore. ...
- webapi拦截请求
[AttributeUsage(AttributeTargets.Method)] public class WebApiSensitive : ActionFilterAttribute { pub ...
- Asp.Net 拦截请求自定义处理
需求: 在Aps.Net 应用中,对于浏览器请求的部分url的地址自定义处理,不交给路由系统或页面. 解决方案: 在全局文件Global.asax中 ,提供Application_BeginReque ...
- Charles拦截请求
一.通过Charles抓包,可拦截请求并篡改交互信息 1.可篡改客户端向服务器发起的请求信息(服务器收到的是假消息) 2.可篡改服务器返回给客户端的响应结果(客户端看到的是假消息) 二.篡改用户请求 ...
- springmvc拦截请求
springmvc.xml <!--拦截请求 --> <mvc:interceptors> <mvc:interceptor> <!-- 要拦截的请求类型 / ...
- 使用框架时,在web.xml中配置servlet时,拦截请求/和/*的区别。
关于servlet的拦截设置,之前看了好多,说的都不太清除,明白. 最近明白了一些,总的来说就是保证拦截所有用户请求的同时,放行静态资源. 现整理如下: 一.我们都知道在基于Spring的Applic ...
随机推荐
- C语言博客作业05--指针
1.本章学习总结 1.1 思维导图 1.2 本章学习体会及代码量学习体会 1.2.1 学习体会 1.2.2 代码累计 2.PTA总分 2.1截图PTA中函数题目集的排名得分 2.2 我的总分: 3.P ...
- MySQL逻辑备份into outfile
MySQL 备份之 into outfile 逻辑数据导出(备份) 用法: select xxx into outfile '/path/file' from table_name; mysql> ...
- Flexbox(弹性盒模型)完全指南
Flexbox(弹性盒模型)布局完全指南 Github:sueRimn 来源:A guide to Flexbox 这个指南讲诉了flexbox的所有内容,重点介绍了父元素(flex容器)和子元素(f ...
- c/c++程序连接mysql
1.libmysql.dll添加到System32文件夹 “regsvr32 libmysql.dll”注册 2.项目-->属性-->c/c++-->常规-->附加包含目录-- ...
- POJ-3494 Largest Submatrix of All 1’s (单调栈)
Largest Submatrix of All 1’s Time Limit: 5000MS Memory Limit: 131072K Total Submissions: 8551 Ac ...
- 第二周java学习总结
学号 20175206 <Java程序设计>第二周学习总结 教材学习内容总结 第二章是基本数据类型与数组,第三章是运算符.表达式和语句的内容.如果说第一章是让我们了解JAVA,那么第二章和 ...
- vue(初探预渲染)
---恢复内容开始--- 一.前言 1.简介预渲染 2.案例演示(不配置预渲染) 3.配置预渲染, 二.主要内容 1.简 ...
- hadoop记录-hadoop常用
1.hdfs目录配额 #设置配额目录hdfs dfsadmin -setSpaceQuota 10T /user/hive/warehouser/tmp查看配额目录信息hdfs dfs -count ...
- 实现Map接口(hash原理)
闲来无事,就实现一个简单的map来练练手吧! HashMap的底层实现主要是基于数组和链表来实现的,HashMap中通过key的hashCode来计算hash值的,由这个hash值计算在数组中的位置, ...
- IDEA2019激活码集合(非盈利)
56ZS5PQ1RF-eyJsaWNlbnNlSWQiOiI1NlpTNVBRMVJGIiwibGljZW5zZWVOYW1lIjoi5q2j54mI5o6I5p2DIC4iLCJhc3NpZ25lZ ...