springboot三种过滤功能的使用与比较

若要实现对请求的过滤,有三种方式可供选择:filter、interceptort和aop。本文主要讨论三种拦截器的使用场景与使用方式。

下文中的举例功能是计算每个请求的从开始到结束的时间,例子来源是慕课网。

一、filter

特点:可以获取原始的ServletRequest,但无法获取具体方法

实现:

1.继承javax.servlet.Filter类,

2.@Component注解将其注入到框架中

3.实现其中的dofilter方法,所有的请求都会经过该方法,可以在此计算出每个请求的耗时,代码如下:

 1 package com.zzy.web.filter;
 2 
 3 import java.io.IOException;
 4 import java.util.Date;
 5 
 6 import javax.servlet.Filter;
 7 import javax.servlet.FilterChain;
 8 import javax.servlet.FilterConfig;
 9 import javax.servlet.ServletException;
10 import javax.servlet.ServletRequest;
11 import javax.servlet.ServletResponse;
12 
13 import org.springframework.stereotype.Component;
14 
15 @Component
16 public class TimeFilter implements Filter{
17 
18     @Override
19     public void init(FilterConfig filterConfig) throws ServletException {
20         // TODO Auto-generated method stub
21         System.out.println("filter init");
22         
23     }
24 
25     @Override
26     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
27             throws IOException, ServletException {
28         // TODO Auto-generated method stub
29         Long startTime = new Date().getTime();
30         System.out.println("filter 请求开始时间:"+ startTime);
31         chain.doFilter(request, response);
32          Long endTime = new Date().getTime();
33         System.out.println("filter 请求结束时间:" + endTime +",请求耗时:" + (endTime - startTime));
34         
35     }
36 
37     @Override
38     public void destroy() {
39         // TODO Auto-generated method stub
40         
41     }
42 
43 }

注:如果有的框架没有@Component 这个注解,可以自己写一个配置类,在该类中指定过滤器,而且还可以指定过滤的url,配置类如下:

 1 package com.zzy.web.config;
 2 
 3 import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
 4 
 5 import java.util.ArrayList;
 6 import java.util.List;
 7 
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.boot.web.servlet.FilterRegistrationBean;
10 import org.springframework.context.annotation.Bean;
11 import org.springframework.context.annotation.Configuration;
12 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
13 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
14 
15 import com.zzy.web.filter.TimeFilter;
16 import com.zzy.web.interceptor.TimeInterceptor;
17 
18 @Configuration
19 public class WebConfig extends WebMvcConfigurerAdapter {
20     
21     @Autowired
22     private TimeInterceptor timeInterceptor;
23     
24 //    @Override
25 //    public void addInterceptors(InterceptorRegistry registry) {
26 //        // TODO Auto-generated method stub
27 //        registry.addInterceptor(timeInterceptor);
28 //    }
29     
30     @Bean
31     public FilterRegistrationBean timeFilter() {
32         FilterRegistrationBean registrationBean = new FilterRegistrationBean();
33         TimeFilter timeFilter = new TimeFilter();
34         registrationBean.setFilter(timeFilter);
35         List<String> urls = new ArrayList<>();
36         urls.add("/user/*");
37         registrationBean.setUrlPatterns(urls);
38         return registrationBean;
39     }
40 
41 }

 

 

二、interceptor

特点:可以获取到原始的request和请求的方法,但无法获取方法的具体参数的值。

实现:

1.继承HandlerInterceptor接口

2.请求前的逻辑写在prehandle(请求前调用)

3.请求后的逻辑写在posthandle(请求成功后调用,失败则不调用)

4.请求后,不管成功失败都会调用aftercompletion。

5.intceptor方式继承了之后还没起作用,还需要在配置类里面加一下,把刚声明的拦截器注册一下。

代码示例:

 1 package com.zzy.web.interceptor;
 2 
 3 import java.util.Arrays;
 4 import java.util.Date;
 5 
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 
 9 import org.springframework.stereotype.Component;
10 import org.springframework.web.method.HandlerMethod;
11 import org.springframework.web.servlet.HandlerInterceptor;
12 import org.springframework.web.servlet.ModelAndView;
13 @Component
14 public class TimeInterceptor implements HandlerInterceptor {
15 
16     @Override
17     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
18             throws Exception {
19         // TODO Auto-generated method stub
20         System.out.println("interceptor 执行preHandle");
21 
22         request.setAttribute("startTime", new Date().getTime());
23         return true;
24     }
25 
26     @Override
27     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
28             ModelAndView modelAndView) throws Exception {
29         // TODO Auto-generated method stub
30         Long startTime = Long.parseLong(request.getAttribute("startTime").toString());
31         Long endTime = new Date().getTime();
32         System.out.println("interceptor 执行postHandle");
33         System.out.println("interceptor 请求类:"+((HandlerMethod)handler).getBean().getClass().getName());
34         System.out.println("interceptor 请求方法:"+((HandlerMethod)handler).getMethod());
35 //        System.out.println("interceptor 请求参数:");
36 //        Arrays.asList(((HandlerMethod)handler).getMethodParameters()).stream().forEach(arg->System.out.println(arg));
37         System.out.println("interceptor 请求耗时:" + (endTime - startTime));
38 
39     }
40 
41     @Override
42     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
43             throws Exception {
44         // TODO Auto-generated method stub
45         Long startTime = Long.parseLong(request.getAttribute("startTime").toString());
46         Long endTime = new Date().getTime();
47         System.out.println("interceptor 执行afterCompletion");
48         System.out.println("interceptor 请求类:"+((HandlerMethod)handler).getBean().getClass().getName());
49         System.out.println("interceptor 请求方法:"+((HandlerMethod)handler).getMethod());
50         System.out.println("interceptor 请求耗时:" + (endTime - startTime));
51         System.out.println("interceptor 请求异常:" + ex);
52 
53     }
54 
55 }

配置类如下:

 1 package com.zzy.web.config;
 2 
 3 import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
 4 
 5 import java.util.ArrayList;
 6 import java.util.List;
 7 
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.boot.web.servlet.FilterRegistrationBean;
10 import org.springframework.context.annotation.Bean;
11 import org.springframework.context.annotation.Configuration;
12 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
13 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
14 
15 import com.zzy.web.filter.TimeFilter;
16 import com.zzy.web.interceptor.TimeInterceptor;
17 
18 @Configuration
19 public class WebConfig extends WebMvcConfigurerAdapter {
20     
21     @Autowired
22     private TimeInterceptor timeInterceptor;
23     
24     @Override
25     public void addInterceptors(InterceptorRegistry registry) {
26         // TODO Auto-generated method stub
27         registry.addInterceptor(timeInterceptor);
28     }
29 
30 
31 }

 

三、aop

特点:能拿到方法和具体参数的值,但是拿不到原始的servletrequest的信息。

实现:

1.使用@aspect注解

2.@execution声明切面,声明切面的语法可参考官网https://docs.spring.io/spring/docs/4.3.18.RELEASE/spring-framework-reference/htmlsingle/#aop-pointcuts

3.使用@Around(方法前和方法后),@Before(方法前)或@After(方法后)

以下为@Around举例,代码如下:

 1 package com.zzy.web.aspect;
 2 
 3 import java.util.Date;
 4 
 5 import org.aspectj.lang.ProceedingJoinPoint;
 6 import org.aspectj.lang.annotation.Around;
 7 import org.aspectj.lang.annotation.Aspect;
 8 import org.codehaus.jackson.map.ObjectMapper;
 9 import org.springframework.stereotype.Component;
10 
11 @Aspect
12 @Component
13 public class TimeAspect {
14 
15     @Around("execution(* com.zzy.web.controller.UserController.*(..))")
16     public Object test(ProceedingJoinPoint pjp) throws Throwable {
17         Long startTime = new Date().getTime();
18         Object[] args = pjp.getArgs();
19         for (Object arg : args) {
20             System.out.println("aspect 参数:" + arg);
21         }
22         Object object = pjp.proceed();
23         System.out.println("aspect 请求耗时:" + (new Date().getTime() - startTime));
24         System.out.println("aspect 请求结果:" + new ObjectMapper().writeValueAsString(object));
25 
26         return object;
27 
28     }
29 }

 下图是三种方式的拦截顺序,图片来自慕课网:

 

 

 

转载于:https://www.cnblogs.com/zuxiaoyuan/p/9702363.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/279281.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

后缀的形容词_构词法(18)构成形容词的常见后缀 3

即时练习一、按要求改写下列单词。1. Japan →___________ adj. 日本(人)的2. Canton →_________ adj. 广东(人)的3. Vietnam →__________ adj. 越南(人)的4. Europe →__________ adj. 欧洲(人)的5. India → ________ adj. 印度(人)的6. Africa →_______ adj. 非洲(人)的7…

批量删除推文_如何搜索(和删除)您的旧推文

批量删除推文“The internet never forgets” is an aphorism that isn’t entirely true, but it’s worth thinking about whenever you post to social media. If you think your Twitter profile needs a bit of a scrub, here’s how to search and delete those old twee…

智能记忆功能nest_如何设置和安装Nest Protect智能烟雾报警器

智能记忆功能nestIf you want to add a bit more convenience and safety to your home’s smoke alarm setup, the Nest Protect comes with a handful of great features to make that a reality. Here’s how to set it up and what all you can do with it. 如果您想为您的…

网格自适应_ANSYS 非线性自适应(NLAD)网格划分及应用举例

文章来源&#xff1a;安世亚太官方订阅号&#xff08;搜索&#xff1a;Peraglobal&#xff09;在复杂的结构设计分析中&#xff0c;通常很难确定在高应力区域中是否生成适当的细化网格。在做非线性大应变分析仿真时&#xff0c;可能由于单元变形过大&#xff0c;导致网格畸变&a…

python---[列表]lsit

内置数据结构&#xff08;变量类型&#xff09; -list -set -dict -tuple -list&#xff08;列表&#xff09; -一组又顺序的数据组合 -创建列表 -空列表 list1 []        print(type(list1))        print(list1)        list2 [100]       …

唤醒计算机运行此任务_如何停止Windows 8唤醒计算机以运行维护

唤醒计算机运行此任务Windows 8 comes with a new hybrid boot system, this means that your PC is never really off. It also means that Windows has the permission to wake your PC as it needs. Here’s how to stop it from waking up your PC to do maintenance tasks…

转整型_SPI转can芯片CSM300详解、Linux驱动移植调试笔记

一口君最近移植了一款SPI转CAN的芯片CSM300A&#xff0c;在这里和大家做个分享。一、CSM300概述CSM300(A)系列是一款可以支持 SPI / UART 接口的CAN模块。1. 简介CSM300(A)系列隔离 SPI / UART 转 CAN 模块是集成微处理器、 CAN 收发器、 DC-DC 隔离电源、 信号隔离于一体的通信…

matlab练习程序(二值图像连通区域标记法,一步法)

这个只需要遍历一次图像就能够完全标记了。我主要参考了WIKI和这位兄弟的博客&#xff0c;这两个把原理基本上该介绍的都介绍过了&#xff0c;我也不多说什么了。一步法代码相比两步法真是清晰又好看&#xff0c;似乎真的比两步法要好很多。 代码如下&#xff1a; clear all; c…

pc微信不支持flash_在出售PC之前,如何取消对Flash内容的授权

pc微信不支持flashWhen it comes to selling your old digital equipment you usually should wipe it of all digital traces with something like DBAN, however if you can’t there are some precautions you should take–here’s one related to Flash content you may h…

绘制三维散点图_SPSS统计作图教程:三维散点图

作者&#xff1a;豆沙包&#xff1b;审稿&#xff1a;张耀文1、问题与数据最大携氧能力是身体健康的一项重要指标&#xff0c;但检测该指标成本较高。研究者想根据性别、年龄、体重、运动后心率等指标建立预测最大携氧能力的模型&#xff0c;招募了100名研究对象&#xff0c;测…

使用lodash防抖_什么,lodash 的防抖失效了?

戳蓝字「前端技术优选」关注我们哦&#xff01;作者&#xff1a;yeyan1996https://juejin.im/post/6892577964458770445应某人的要求被迫营业&#xff0c;望各位看官不要吝啬手中的赞-。-背景在使用 uni-app 开发小程序时&#xff0c;有个填写表单的需求&#xff0c;包含两个输…

Ubuntu 12.10中的8个新功能,Quantal Quetzal

Ubuntu 12.10 has been released and you can download it now. From better integration with web apps and online services to improvements in Unity, there are quite a few changes – although none of them are huge or groundbreaking. Ubuntu 12.10已发布&#xff0c…

背单词APP调研分析

前言&#xff1a;随着我国网络经济重心向移动端的转移&#xff0c;移动教育领域获得的关注度在持续放大。互联网的发展和移动设备的普及&#xff0c;我们开始在移动设备上学习&#xff0c;各种学习教育软件如雨后春笋&#xff0c;越来越多&#xff0c;就背单词软件来说&#xf…

cdh中使用hue使用教程_我可以在户外使用Philips Hue灯泡吗?

cdh中使用hue使用教程Philips Hue lights are great to have in your house, and they can add a lot of convenience to your living space. However, what if you want to use these smart bulbs outdoors in porch lights or flood lights? Will Philips Hue bulbs work pr…

弄断过河电缆_你说的是:剪断电缆线

弄断过河电缆Earlier this week we asked you if you’d cut the cable and switched to alternate media sources to get your movie and TV fix. You responded and we’re back with a What You Said roundup. 本周早些时候&#xff0c;我们问您是否要切断电缆并切换到其他媒…

路由销毁上一页_路由器原理(数据通信)

路由&#xff1a;对数据包选择路径的过程路由器(也叫网关)智能选择数据传输路由的设备&#xff0c;其端口数量较少&#xff01;功能&#xff1a;连接网络1.连接异构网络以太网、ATM网络、FDDI网络2.连接远程网络局域网、广域网隔离广播将广播隔离在局域网内路由选择网络安全地址…

您可能没有使用的最佳三星Galaxy功能

Samsung packs its flagship phones with a slew of features—some are even better than stock Android. Either way, there are a lot of things on these phones that you may not be using. Here are some of the best. 包三星旗舰手机用的特性-摆有的甚至比普通的Android…

win7更新错误0x800b0109_win7更新漏洞后产生0x0000006B蓝屏的解决方法图解

这几天不少网友在使用win7更新补丁后就蓝屏了&#xff0c;代码为0x0000006b。发生这一蓝屏问题的都是安装了2016年四月份推出的安全更新补丁&#xff0c;安装后就出现蓝屏&#xff0c;有的网友表示没问题&#xff0c;有的直接蓝了。这个蓝屏重启后依旧&#xff0c;安全模式进不…

如何使用facebook_如果每个人都已经开始使用Facebook,Facebook能否继续发展?

如何使用facebookThere are only so many people on earth, and so many hours in the day. Is that starting to limit the growth of social media? 地球上只有那么多人&#xff0c;一天中有很多小时。 这是否开始限制社交媒体的增长&#xff1f; Think about how much time…

2018-10-03-Python全栈开发-day60-django序列化-part3

联合唯一 clean_字段方法只能对某个字段进行检查&#xff0c;当clean方法执行完之后&#xff0c;最后还会执行clean方法&#xff0c;在clean方法中&#xff0c;可以通过获取数据字典中的值然后进行验证 from django.shortcuts import render,HttpResponsefrom django import fo…