Spring 拦截器实现+后台原理(HandlerInterceptor)
过滤器跟拦截器的区别
spring mvc的拦截器是只拦截controller而不拦截jsp,html 页面文件的。这就用到过滤器filter了,filter是在servlet前执行的,你也可以理解成过滤器中包含拦截器,一个请求过来 ,先进行过滤器处理,看程序是否受理该请求 。 过滤器放过后 , 程序中的拦截器进行处理 。
1、拦截器不依赖servlet容器,过滤器依赖;
2、拦截器是基于java反射机制来实现的,过滤器基于回调
过滤器:关注web请求;
拦截器:关注方法调用;
Spring拦截器分类
spring中拦截器主要分两种,一个是HandlerInterceptor,一个是MethodInterceptor。
HandlerInterceptor
HandlerInterceptor是springMVC项目中的拦截器,它拦截的目标是请求的地址,比MethodInterceptor先执行。
HandlerInterceptor拦截的是请求地址,所以针对请求地址做一些验证、预处理等操作比较合适。当你需要统计请求的响应时间时MethodInterceptor将不太容易做到,因为它可能跨越很多方法或者只涉及到已经定义好的方法中一部分代码。
实现一个HandlerInterceptor拦截器可以直接实现HandlerInterceptor接口,也可以继承HandlerInterceptorAdapter类。
看下UML:
HandlerInterceptorAdapter.class
public abstract class HandlerInterceptorAdapter implements AsyncHandlerInterceptor {
public HandlerInterceptorAdapter() {
}
//在业务处理器处理请求之前被调用
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
//在业务处理器处理请求完成之后,生成视图之前执行
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
// 在DispatcherServlet完全处理完请求之后被调用,可用于清理资源
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
} public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
}
}
执行顺序如图:
具体体现在 DispatcherServlet.class doDispatch() 方法中,看下源码:
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
boolean multipartRequestParsed = false;
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); try {
try {
ModelAndView mv = null;
Object dispatchException = null; try {
processedRequest = this.checkMultipart(request);
multipartRequestParsed = processedRequest != request;
mappedHandler = this.getHandler(processedRequest);
if (mappedHandler == null) {
this.noHandlerFound(processedRequest, response);
return;
} HandlerAdapter ha = this.getHandlerAdapter(mappedHandler.getHandler());
String method = request.getMethod();
boolean isGet = "GET".equals(method);
if (isGet || "HEAD".equals(method)) {
long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
if ((new ServletWebRequest(request, response)).checkNotModified(lastModified) && isGet) {
return;
}
} if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
} mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
if (asyncManager.isConcurrentHandlingStarted()) {
return;
} this.applyDefaultViewName(processedRequest, mv);
mappedHandler.applyPostHandle(processedRequest, response, mv);
} catch (Exception var20) {
dispatchException = var20;
} catch (Throwable var21) {
dispatchException = new NestedServletException("Handler dispatch failed", var21);
} this.processDispatchResult(processedRequest, response, mappedHandler, mv, (Exception)dispatchException);
} catch (Exception var22) {
this.triggerAfterCompletion(processedRequest, response, mappedHandler, var22);
} catch (Throwable var23) {
this.triggerAfterCompletion(processedRequest, response, mappedHandler, new NestedServletException("Handler processing failed", var23));
} } finally {
if (asyncManager.isConcurrentHandlingStarted()) {
if (mappedHandler != null) {
mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
}
} else if (multipartRequestParsed) {
this.cleanupMultipart(processedRequest);
} }
}
现在需要一个简单的demo,深入了解几个方法:
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; public class SecurityInterceptor extends HandlerInterceptorAdapter { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("SecurityInterceptor >>>>>>>>1"); return true;
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class WebSecurityConfig extends WebMvcConfigurationSupport { @Bean
public SecurityInterceptor getSecurityInterceptor() {
return new SecurityInterceptor();
} @Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor()); // 排除配置
addInterceptor.excludePathPatterns("/403");
addInterceptor.excludePathPatterns("/toLogin");
addInterceptor.excludePathPatterns("/login**"); // 拦截配置
addInterceptor.addPathPatterns("/**");
}
}
启动工程(springboot工程):
请求:http://localhost:8080/toLogin ,因为配置了排除设置,后台无打印。
请求:http://localhost:8080/userInfo/userAdd,后台有打印。
发散:如果是多个拦截器,他们preHandle、postHandle、afterCompletion方法执行顺序是什么?
看下demo:
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; public class SecurityInterceptor extends HandlerInterceptorAdapter { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("SecurityInterceptor.preHandle >>>>>>>>1"); return true;
} public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
System.out.println("SecurityInterceptor.postHandle >>>>>>>>1");
} public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
System.out.println("SecurityInterceptor.afterCompletion >>>>>>>>1");
}
}
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class HelloInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("HelloInterceptor.preHandle >>>>>>>>3");
return true;
} public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
System.out.println("HelloInterceptor.postHandle >>>>>>>>3");
} public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
System.out.println("HelloInterceptor.afterCompletion >>>>>>>>3");
}
}
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class RoleAuthorizationInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("RoleAuthorizationInterceptor.preHandle >>>>>>>>2");
return true;
} public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
System.out.println("RoleAuthorizationInterceptor.postHandle >>>>>>>>2");
} public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
System.out.println("RoleAuthorizationInterceptor.afterCompletion >>>>>>>>2");
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class WebSecurityConfig extends WebMvcConfigurationSupport { @Bean
public SecurityInterceptor getSecurityInterceptor() {
return new SecurityInterceptor();
} @Bean
public HelloInterceptor getHelloInterceptor() {
return new HelloInterceptor();
} @Bean
public RoleAuthorizationInterceptor getRoleAuthorizationInterceptor() {
return new RoleAuthorizationInterceptor();
} @Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor()); // 排除配置
addInterceptor.excludePathPatterns("/403");
addInterceptor.excludePathPatterns("/toLogin");
addInterceptor.excludePathPatterns("/login**"); // 拦截配置
addInterceptor.addPathPatterns("/**"); InterceptorRegistration roleInter = registry.addInterceptor(getRoleAuthorizationInterceptor());
// 拦截配置
roleInter.addPathPatterns("/**"); InterceptorRegistration helloInter = registry.addInterceptor(getHelloInterceptor());
helloInter.addPathPatterns("/**"); }
}
执行结果:
如果拦截器的preHandle()返回false,结果会怎样,改下demo:
WebSecurityConfig.java
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor()); // 排除配置
/*addInterceptor.excludePathPatterns("/403");
addInterceptor.excludePathPatterns("/toLogin");
addInterceptor.excludePathPatterns("/login**");*/ // 拦截配置
addInterceptor.addPathPatterns("/**"); InterceptorRegistration roleInter = registry.addInterceptor(getRoleAuthorizationInterceptor());
// 拦截配置
roleInter.addPathPatterns("/**"); InterceptorRegistration helloInter = registry.addInterceptor(getHelloInterceptor());
helloInter.addPathPatterns("/**"); }
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("RoleAuthorizationInterceptor.preHandle >>>>>>>>2");
return false;
}
其他不变,运行结果:
通过源码分析,当prehandle返回false,则执行triggerAfterCompletion()执行拦截器的afterCompletion()方法。
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
HandlerInterceptor[] interceptors = this.getInterceptors();
if (!ObjectUtils.isEmpty(interceptors)) {
for(int i = 0; i < interceptors.length; this.interceptorIndex = i++) {
HandlerInterceptor interceptor = interceptors[i];
if (!interceptor.preHandle(request, response, this.handler)) {
this.triggerAfterCompletion(request, response, (Exception)null);
return false;
}
}
} return true;
}
如果preHandle都返回true,postHandle()异常,又会是什么情况呢?
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
System.out.println("RoleAuthorizationInterceptor.postHandle >>>>>>>>2");
throw new NullPointerException();
}
结果:
结论:
1、如果多个拦截器,执行顺序:preHandle() :123 ,postHandle():321,afterCompletion():321
2、preHandle() 返回false,不会往下执行
3、preHandle()返回true的拦截器,必然会执行他的afterCompletion();
4、如果preHandle()都返回true,有一个拦截器的postHandle()抛出异常,则后面拦截器的postHandle()不会执行。(注意:写代码时要注意)
参考:
https://www.cnblogs.com/niceyoo/p/8735637.html
Spring 拦截器实现+后台原理(HandlerInterceptor)的更多相关文章
- Spring 拦截器实现+后台原理(MethodInterceptor)
MethodInterceptor MethodInterceptor是AOP项目中的拦截器(注:不是动态代理拦截器),区别与HandlerInterceptor拦截目标时请求,它拦截的目标是方法. ...
- [十四]SpringBoot 之 Spring拦截器(HandlerInterceptor)
过滤器属于Servlet范畴的API,与spring 没什么关系. Web开发中,我们除了使用 Filter 来过滤请web求外,还可以使用Spring提供的HandlerInterceptor(拦截 ...
- Spring 拦截器——HandlerInterceptor
采用Spring拦截器的方式进行业务处理.HandlerInterceptor拦截器常见的用途有: 1.日志记录:记录请求信息的日志,以便进行信息监控.信息统计.计算PV(Page View)等. 2 ...
- Spring拦截器和过滤器
什么是拦截器 拦截器(Interceptor): 用于在某个方法被访问之前进行拦截,然后在方法执行之前或之后加入某些操作,其实就是AOP的一种实现策略.它通过动态拦截Action调用的对象,允许开发者 ...
- spring 拦截器简介
spring 拦截器简介 常见应用场景 1.日志记录:记录请求信息的日志,以便进行信息监控.信息统计.计算PV(Page View)等.2.权限检查:如登录检测,进入处理器检测检测是否登录,如果没有直 ...
- struts2拦截器的实现原理
拦截器(interceptor)是Struts2最强大的特性之一,也可以说是struts2的核心,拦截器可以让你在Action和result被执行之前或之后进行一些处理.同时,拦截器也可以让你将通用的 ...
- Spring拦截器中通过request获取到该请求对应Controller中的method对象
背景:项目使用Spring 3.1.0.RELEASE,从dao到Controller层全部是基于注解配置.我的需求是想在自定义的Spring拦截器中通过request获取到该请求对应于Control ...
- spring拦截器中修改响应消息头
问题描述 前后端分离的项目,前端使用Vue,后端使用Spring MVC. 显然,需要解决浏览器跨域访问数据限制的问题,在此使用CROS协议解决. 由于该项目我在中期加入的,主要负责集成shiro框架 ...
- struts2拦截器的实现原理及源码剖析
拦截器(interceptor)是Struts2最强大的特性之一,也可以说是struts2的核心,拦截器可以让你在Action和result被执行之前或之后进行一些处理.同时,拦截器也可以让你将通用的 ...
随机推荐
- 【专家坐堂Q&A】在 petalinux-config 中选择外部来源时,可将符号链路添加内核来源目录树
问题描述 作为 petalinux-config 菜单的一部分,现在可以将 Linux 内核指定为外部来源. 如果选择了该选项,可为内核来源目录树添加两个符号链路. 这会带来两个问题: 1. 符号链路 ...
- day28 网络编程
网络编程 什么是网络编程? 编写基于网络的应用程序的过程称之为网络编程 一.CS构架 C/S构架 服务器和客户端之间用网线连接 提供数据的计算机称为服务器,访问数据的计算机称为客户端 二.网络通讯的基 ...
- topcoder srm 550 div1
problem1 link 因为数据比较小,直接开一个二维数组记录哪些格子已经遍历,哪些还没有.进行模拟即可. problem2 link 模拟一些小数据,可以发现,AB的形状以及要求的区间是下面的样 ...
- 4. 多重背包问题 I
多重背包问题 I 描述 有 NN 种物品和一个容量是 VV 的背包. 第 ii 种物品最多有 sisi 件,每件体积是 vivi,价值是 wiwi. 求解将哪些物品装入背包,可使物品体积总和不超过背包 ...
- 终于记住回车和换行cr lf的来由和含义了 -参考: http://www.cnblogs.com/me115/archive/2011/04/27/2030762.html
回车: carriage return, 是将光标在同一行中, 回到当前行的 行首. 回来的本意就是 返回.. 所以 是同一行的行首. CR 换行: line feed: feed: 饲养(动物); ...
- Miller_Rabin整理笔记
目录 问题 别的 正事 代码 问题 一个数到底是不是素数 别的 首先列一下我们可以求素数的东西 根号暴力求 \(O(nloglogn)\)的埃氏筛 \(O(n)\)的欧拉筛 还有我们要学习的Mille ...
- LIS|计蒜客2019蓝桥杯省赛 B 组模拟赛(一)
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 9; int f[N], a[N]; int n; // ...
- 【做题】UVA-12304——平面计算集合六合一
可真是道恶心题-- 首先翻译一下6个任务: 给出一个三角形,求它的外界圆. 给出一个三角形,求它的内接圆. 给出一个圆和一个点,求过这个点的切线的倾斜角\(\alpha \in [0,180)\).( ...
- 安装ubuntu的坑&RHEL7配置
1.需要其他设置->分区,分区需要有/根目录分区和swap空间,后者文件系统类型选择swap,其他都是ext4 2.普通配置电脑,安装16.04.5 LTS,不要安装最新的,安装重启后卡在那里, ...
- MD5+salt 工具类
import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.securit ...