方式:

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的更多相关文章

  1. Springboot通过拦截器拦截请求信息收集到日志

    1.需求 最近在工作中遇到的一个需求,将请求中的客户端类型.操作系统类型.ip.port.请求方式.URI以及请求参数值收集到日志中,网上找资料说用拦截器拦截所有请求然后收集信息,于是就开始了操作: ...

  2. spring Boot使用AOP统一处理Web请求日志记录

    1.使用spring boot实现一个拦截器 1.引入依赖: <dependency>   <groupId>org.springframework.boot</grou ...

  3. .net core MVC 通过 Filters 过滤器拦截请求及响应内容

    前提: 需要nuget   Microsoft.Extensions.Logging.Log4Net.AspNetCore   2.2.6: Swashbuckle.AspNetCore 我暂时用的是 ...

  4. asp.net core 使用中间件拦截请求和返回数据,并对数据进行加密解密。

    原文:asp.net core 使用中间件拦截请求和返回数据,并对数据进行加密解密. GitHub demo https://github.com/zhanglilong23/Asp.NetCore. ...

  5. webapi拦截请求

    [AttributeUsage(AttributeTargets.Method)] public class WebApiSensitive : ActionFilterAttribute { pub ...

  6. Asp.Net 拦截请求自定义处理

    需求: 在Aps.Net 应用中,对于浏览器请求的部分url的地址自定义处理,不交给路由系统或页面. 解决方案: 在全局文件Global.asax中 ,提供Application_BeginReque ...

  7. Charles拦截请求

    一.通过Charles抓包,可拦截请求并篡改交互信息 1.可篡改客户端向服务器发起的请求信息(服务器收到的是假消息) 2.可篡改服务器返回给客户端的响应结果(客户端看到的是假消息) 二.篡改用户请求 ...

  8. springmvc拦截请求

    springmvc.xml <!--拦截请求 --> <mvc:interceptors> <mvc:interceptor> <!-- 要拦截的请求类型 / ...

  9. 使用框架时,在web.xml中配置servlet时,拦截请求/和/*的区别。

    关于servlet的拦截设置,之前看了好多,说的都不太清除,明白. 最近明白了一些,总的来说就是保证拦截所有用户请求的同时,放行静态资源. 现整理如下: 一.我们都知道在基于Spring的Applic ...

随机推荐

  1. python爬虫基础应用----爬取校花网视频

    一.爬虫简单介绍 爬虫是什么? 爬虫是首先使用模拟浏览器访问网站获取数据,然后通过解析过滤获得有价值的信息,最后保存到到自己库中的程序. 爬虫程序包括哪些模块? python中的爬虫程序主要包括,re ...

  2. Verilog语言实现并行(循环冗余码)CRC校验

    1 前言 (1)    什么是CRC校验? CRC即循环冗余校验码:是数据通信领域中最常用的一种查错校验码,其特征是信息字段和校验字段的长度可以任意选定.循环冗余检查(CRC)是一种数据传输检错功能, ...

  3. 【THUSC2017】【LOJ2979】换桌 线段树 网络流

    题目大意 有 \(n\) 个圆形的桌子排成一排,每个桌子有 \(m\) 个座位. 最开始每个位置上都有一个人.现在每个人都要重新选择一个座位,第 \(i\) 桌的第 \(j\) 个人的新座位只能在第 ...

  4. JavaScript基础入门 - 01

    JavaScript入门 - 01 准备工作 在正式的学习JavaScript之前,我们先来学习一些小工具,帮助我们更好的学习和理解后面的内容. js代码位置 首先是如何编写JavaScript代码, ...

  5. 【地图功能开发系列:二】根据地址名称通过百度地图API查询出坐标

    根据地址名称通过百度地图API查询出坐标 百度地图ApiUrl string url = "http://api.map.baidu.com/geocoder?address={0}& ...

  6. VO、DTO、DO、PO

    领域模型中的实体类可细分为4种类型:VO.DTO.DO.PO. PO(Persistent Object):持久化对象,表示持久层的数据结构(如数据库表): DO(Domain Object):领域对 ...

  7. 谈谈JavaScript中继承方式

    聊一聊js中的继承 一.简单继承---使用原型赋值的方式继承,将实例化的对象,赋值给子级的原型 父级构造函数 function Parent(param) { this.name = 'parent' ...

  8. eclipse 包 取消代码第一行package包名 自动补全时取消自动引入包名 修改名字 取消引用 自动导入publilc static void main(String[] args) {}

    --项目 --包 包是为了管理类文件,同个包下不允许同名类文件,但不同包就可以,把类放在包里是规范 (https://zhidao.baidu.com/question/239471930532952 ...

  9. linux date -s

    修改linux的时间可以使用date指令 修改日期: 时间设定成2009年5月10日的命令如下: #date -s 05/10/2009 修改时间: 将系统时间设定成上午10点18分0秒的命令如下.  ...

  10. 1.9 分布式协调服务-Zookeeper(二)

    zoo.cfg配置文件分析 tickTime=2000  zookeeper中最小的时间单位长度 (ms) initLimit=10  follower节点启动后与leader节点完成数据同步的时间 ...