spring 5.1.2 mvc RequestMappingHandlerMapping 调用handler过程
https://my.oschina.net/zhangxufeng/blog/2177464
https://www.jianshu.com/p/447826c28e37 Interceptors xml文件中配置
调用gethandler方法,会通过request中的url从之前初始化的methodhander中找到最匹配的一个methodhandler,
如果url不能匹配到相应的【mappingRegistry.getMappingsByUrl(lookupPath)】,
则从所有的methodhandler的参数,返回值等都匹配的找【mappingRegistry.getMappings().keySet()】
找到最匹配的methodhandler后,则
在这之前要看下RequestMappingHandlerMapping -> AbstractHandlerMapping 继承WebApplicationObjectSupport --->ApplicationObjectSupport ->ApplicationContextAware
在初始化时会调用 setApplicationContext initApplicationContext detectMappedInterceptors 会把所有的MappedInterceptor的bean加入到adaptedInterceptors list中去
https://www.jianshu.com/p/447826c28e37
//在dispatcher-servlet.xml文件中添加下面代码:
//DefaultInterceptor实现HandlerInterceptor,<mvc:interceptors>配置的时候,直接MappedInterceptor。
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="interceptor.DefaultInterceptor">
</mvc:interceptor>
</mvc:interceptors>
//WebInterceptor实现HandlerInterceptor,<bean <property>>配置的时候,判断后添加到adaptedInterceptors。
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
<property name="interceptors">
<list>
<bean class="interceptor.DefaultInterceptor1" />
</list>
</property>
</bean>
上面配置文件中两种拦截器配置方式会产生两个不同的BeanNameUrlHandlerMapping实例,那个拦截器配置在前那个BeanNameUrlHandlerMapping实例执行;这样的话,后面配置的拦截器将不会被执行,所以在配置拦截器的时候选取一种方式即可。
获取Handler的时序图
AbstractHandlerMapping
/**
* Initializes the interceptors.
* @see #extendInterceptors(java.util.List)
* @see #initInterceptors()
*/
@Override
protected void initApplicationContext() throws BeansException {
//<bean <property>>配置的拦截器如:DefaultInterceptor1
extendInterceptors(this.interceptors);
////<mvc:interceptors>配置的拦截器如:DefaultInterceptor
detectMappedInterceptors(this.adaptedInterceptors);
//将<bean <property>>配置的拦截器添加到对应的拦截器List中
initInterceptors();
}
/**
* Extension hook that subclasses can override to register additional interceptors,
* given the configured interceptors (see {@link #setInterceptors}).
* <p>Will be invoked before {@link #initInterceptors()} adapts the specified
* interceptors into {@link HandlerInterceptor} instances.
* <p>The default implementation is empty.
* @param interceptors the configured interceptor List (never {@code null}), allowing
* to add further interceptors before as well as after the existing interceptors
*/
protected void extendInterceptors(List<Object> interceptors) {
}
/**
* Detect beans of type {@link MappedInterceptor} and add them to the list of mapped interceptors.
* <p>This is called in addition to any {@link MappedInterceptor MappedInterceptors} that may have been provided
* via {@link #setInterceptors}, by default adding all beans of type {@link MappedInterceptor}
* from the current context and its ancestors. Subclasses can override and refine this policy.
* @param mappedInterceptors an empty list to add {@link MappedInterceptor} instances to
*/
protected void detectMappedInterceptors(List<HandlerInterceptor> mappedInterceptors) {
mappedInterceptors.addAll(
BeanFactoryUtils.beansOfTypeIncludingAncestors(
obtainApplicationContext(), MappedInterceptor.class, true, false).values());
}
/**
* Initialize the specified interceptors, checking for {@link MappedInterceptor MappedInterceptors} and
* adapting {@link HandlerInterceptor}s and {@link WebRequestInterceptor HandlerInterceptor}s and
* {@link WebRequestInterceptor}s if necessary.
* @see #setInterceptors
* @see #adaptInterceptor
*/
protected void initInterceptors() {
if (!this.interceptors.isEmpty()) {
for (int i = 0; i < this.interceptors.size(); i++) {
Object interceptor = this.interceptors.get(i);
if (interceptor == null) {
throw new IllegalArgumentException("Entry number " + i + " in interceptors array is null");
}
this.adaptedInterceptors.add(adaptInterceptor(interceptor));
}
}
}
/**
* Look up a handler for the given request, falling back to the default
* handler if no specific one is found.
* @param request current HTTP request
* @return the corresponding handler instance, or the default handler
* @see #getHandlerInternal
*/
@Override
@Nullable
public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
Object handler = getHandlerInternal(request);
if (handler == null) {
handler = getDefaultHandler();
}
if (handler == null) {
return null;
}
// Bean name or resolved handler?
if (handler instanceof String) {
String handlerName = (String) handler;
handler = obtainApplicationContext().getBean(handlerName);
}
// 获取当前系统中配置的Interceptor,将其与handler一起封装为一个HandlerExecutionChain
HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);
if (logger.isTraceEnabled()) {
logger.trace("Mapped to " + handler);
}
else if (logger.isDebugEnabled() && !request.getDispatcherType().equals(DispatcherType.ASYNC)) {
logger.debug("Mapped to " + executionChain.getHandler());
}
// 这里CorsUtils.isCorsRequest()方法判断的是当前请求是否为一个跨域的请求,如果是一个跨域的请求,
// 则将跨域相关的配置也一并封装到HandlerExecutionChain中
if (CorsUtils.isCorsRequest(request)) {
CorsConfiguration globalConfig = this.corsConfigurationSource.getCorsConfiguration(request);
CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);
CorsConfiguration config = (globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig);
executionChain = getCorsHandlerExecutionChain(request, executionChain, config);
}
return executionChain;
}
/**
* Build a {@link HandlerExecutionChain} for the given handler, including
* applicable interceptors.
* <p>The default implementation builds a standard {@link HandlerExecutionChain}
* with the given handler, the handler mapping's common interceptors, and any
* {@link MappedInterceptor MappedInterceptors} matching to the current request URL. Interceptors
* are added in the order they were registered. Subclasses may override this
* in order to extend/rearrange the list of interceptors.
* <p><b>NOTE:</b> The passed-in handler object may be a raw handler or a
* pre-built {@link HandlerExecutionChain}. This method should handle those
* two cases explicitly, either building a new {@link HandlerExecutionChain}
* or extending the existing chain.
* <p>For simply adding an interceptor in a custom subclass, consider calling
* {@code super.getHandlerExecutionChain(handler, request)} and invoking
* {@link HandlerExecutionChain#addInterceptor} on the returned chain object.
* @param handler the resolved handler instance (never {@code null})
* @param request current HTTP request
* @return the HandlerExecutionChain (never {@code null})
* @see #getAdaptedInterceptors()
*/
protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpServletRequest request) {
HandlerExecutionChain chain = (handler instanceof HandlerExecutionChain ?
(HandlerExecutionChain) handler : new HandlerExecutionChain(handler));
String lookupPath = this.urlPathHelper.getLookupPathForRequest(request);
for (HandlerInterceptor interceptor : this.adaptedInterceptors) {
if (interceptor instanceof MappedInterceptor) {
MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor;
//<mvc:interceptors>都会被解析成MappedInterceptor 如果匹配路径,则加入
if (mappedInterceptor.matches(lookupPath, this.pathMatcher)) {
chain.addInterceptor(mappedInterceptor.getInterceptor());
}
}
else {
//将<bean <property>>配置的拦截器添加到对应的拦截器List中
chain.addInterceptor(interceptor);
}
}
return chain;
}
对于拦截器,理论上,Spring是会将所有的拦截器都进行一次调用,对于是否需要进行拦截,都是用户自定义实现的。这里如果对于URI有特殊的匹配,可以使用MappedInterceptor,然后实现其matches()方法,用于判断当前MappedInterceptor是否能够应用于当前request。
AbstractHandlerMethodMapping
// Handler method lookup
/**
* Look up a handler method for the given request.
*/
@Override
protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
this.mappingRegistry.acquireReadLock();
try {
HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request);
return (handlerMethod != null ? handlerMethod.createWithResolvedBean() : null);
}
finally {
this.mappingRegistry.releaseReadLock();
}
}
/**
* Look up the best-matching handler method for the current request.
* If multiple matches are found, the best match is selected.
* @param lookupPath mapping lookup path within the current servlet mapping
* @param request the current request
* @return the best-matching handler method, or {@code null} if no match
* @see #handleMatch(Object, String, HttpServletRequest)
* @see #handleNoMatch(Set, String, HttpServletRequest)
*/
@Nullable
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
List<Match> matches = new ArrayList<>();
// 通过uri直接在注册的RequestMapping中获取对应的RequestMappingInfo列表,需要注意的是,
// 这里进行查找的方式只是通过url进行查找,但是具体哪些RequestMappingInfo是匹配的,还需要进一步过滤
List<T> directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath);
if (directPathMatches != null) {
// 对获取到的RequestMappingInfo进行进一步过滤,并且将过滤结果封装为一个Match列表
addMatchingMappings(directPathMatches, matches, request);
}
if (matches.isEmpty()) {
// No choice but to go through all mappings...
// 如果无法通过uri进行直接匹配,则对所有的注册的RequestMapping进行匹配,这里无法通过uri
// 匹配的情况主要有三种:
// ①在RequestMapping中定义的是PathVariable,如/user/detail/{id};
// ②在RequestMapping中定义了问号表达式,如/user/?etail;
// ③在RequestMapping中定义了*或**匹配,如/user/detail/**
addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, request);
}
if (!matches.isEmpty()) {
Comparator<Match> comparator = new MatchComparator(getMappingComparator(request));
matches.sort(comparator);
Match bestMatch = matches.get(0);
if (matches.size() > 1) {
// 如果匹配结果不止一个,首先会判断是否是跨域请求,如果是,
// 则返回PREFLIGHT_AMBIGUOUS_MATCH,如果不是,则会判断前两个匹配程度是否相同,
// 如果相同则抛出异常
if (logger.isTraceEnabled()) {
logger.trace(matches.size() + " matching mappings: " + matches);
}
if (CorsUtils.isPreFlightRequest(request)) {
return PREFLIGHT_AMBIGUOUS_MATCH;
}
Match secondBestMatch = matches.get(1);
if (comparator.compare(bestMatch, secondBestMatch) == 0) {
Method m1 = bestMatch.handlerMethod.getMethod();
Method m2 = secondBestMatch.handlerMethod.getMethod();
String uri = request.getRequestURI();
throw new IllegalStateException(
"Ambiguous handler methods mapped for '" + uri + "': {" + m1 + ", " + m2 + "}");
}
}
handleMatch(bestMatch.mapping, lookupPath, request);
return bestMatch.handlerMethod;
}
else {
return handleNoMatch(this.mappingRegistry.getMappings().keySet(), lookupPath, request);
}
}
private void addMatchingMappings(Collection<T> mappings, List<Match> matches, HttpServletRequest request) {
for (T mapping : mappings) {
T match = getMatchingMapping(mapping, request);
if (match != null) {
matches.add(new Match(match, this.mappingRegistry.getMappings().get(mapping)));
}
}
}
/**
* Invoked when a matching mapping is found.
* @param mapping the matching mapping
* @param lookupPath mapping lookup path within the current servlet mapping
* @param request the current request
*/
protected void handleMatch(T mapping, String lookupPath, HttpServletRequest request) {
request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, lookupPath);
}
/**
* A thin wrapper around a matched HandlerMethod and its mapping, for the purpose of
* comparing the best match with a comparator in the context of the current request.
*/
private class Match {
private final T mapping;
private final HandlerMethod handlerMethod;
public Match(T mapping, HandlerMethod handlerMethod) {
this.mapping = mapping;
this.handlerMethod = handlerMethod;
}
@Override
public String toString() {
return this.mapping.toString();
}
}
HandlerMethod
public HandlerMethod createWithResolvedBean() {
Object handler = this.bean;
if (this.bean instanceof String) {
Assert.state(this.beanFactory != null, "Cannot resolve bean name without BeanFactory");
String beanName = (String)this.bean;
handler = this.beanFactory.getBean(beanName);
}
return new HandlerMethod(this, handler);
}
private HandlerMethod(HandlerMethod handlerMethod, Object handler) {
Assert.notNull(handlerMethod, "HandlerMethod is required");
Assert.notNull(handler, "Handler object is required");
this.bean = handler;
this.beanFactory = handlerMethod.beanFactory;
this.beanType = handlerMethod.beanType;
this.method = handlerMethod.method;
this.bridgedMethod = handlerMethod.bridgedMethod;
this.parameters = handlerMethod.parameters;
this.responseStatus = handlerMethod.responseStatus;
this.responseStatusReason = handlerMethod.responseStatusReason;
this.resolvedFromHandlerMethod = handlerMethod;
}
spring 5.1.2 mvc RequestMappingHandlerMapping 调用handler过程的更多相关文章
- spring 5.1.2 mvc RequestMappingHandlerMapping 源码初始化过程
RequestMappingHandlerMapping getMappingForMethod RequestMappingHandlerMapping 继承于 AbstractHandlerMet ...
- Spring源码分析之`BeanFactoryPostProcessor`调用过程
前文传送门: Spring源码分析之预启动流程 Spring源码分析之BeanFactory体系结构 本文内容: AbstractApplicationContext#refresh前部分的一点小内容 ...
- Spring Cloud Feign 声明式服务调用
目录 一.Feign是什么? 二.Feign的快速搭建 三.Feign的几种姿态 参数绑定 继承特性 四.其他配置 Ribbon 配置 Hystrix 配置 一.Feign是什么? 通过对前面Sp ...
- ASP.NET请求过程-从源码角度研究MVC路由、Handler、控制器
路由常用对象 RouteBase 用作表示 ASP.NET 路由的所有类的基类. 就是路由的一个基础抽象类. // // 摘要: // 用作表示 ASP.NET 路由的所有类的基类. [ ...
- Spring结合Quartz实现多任务定时调用(转载)
Quartz框架提供了丰富的任务调度支持,比如,在 何时执行何种任务,它是一个开源的由OpenSymphony维护的项目,开发者能够在Java EE,或单独的Java SE应用中使用它.无论是简单的任 ...
- Aspnet MVC 异步调用
一个简图来描述下Aspnet MVC下的异步调用 { request } / \/ -------ISS------- > work thread | \ | \ route - aysn co ...
- ajax调用handler,使用HttpWebRequest访问WCF服务
引言 随着手机及移动设备的普及,移动端的应用也进入了热潮.以前PC端的门户网站,大多也均推出了适配移动设备的网站或者APP,再差的也注册了个公众号.在移动应用开发中,目前据我所了解到的解决方案有:1. ...
- MVC 5 调用存储过程参数配置方法-Procedure or function 'UP_***' expects parameter '@****', which was not supplied.
MVC 5 调用存储过程参数配置方法-Procedure or function 'UP_***' expects parameter '@****', which was not supplied. ...
- 自己动手写Spring框架--IOC、MVC
对于一名Java开发人员,我相信没有人不知道 Spring 框架,而且也能够轻松就说出 Spring 的特性-- IOC.MVC.AOP.ORM(batis). 下面我想简单介绍一下我写的轻量级的 S ...
随机推荐
- c语言:第二次作业,循环结构
1.本章学习总结(2分) 1.1 思维导图 1.2 本章学习体会及代码量学习体会 1.2.1 学习体会 循环相比分支和顺序结构难了许多,相对的来说我的c语言的基础比之前有提高,但是还是很多题想了很久也 ...
- 3D Math Keynote 3
[3D Math Keynote 3] 1.球的表面积 Surface.球的体积 Volumn: 2.当物体旋转后,如果通过变换后的旧AABB来顶点来计算新的AABB顶点,则生成的新AABB可能比实际 ...
- scrapy 断点续爬
第一步:安装berkeleydb数据库 第二部:pip install bsddb3 第三部:pip install scrapy-deltafetch 第四部: settings.py设置 SPID ...
- contains用法
判断List<UserInfoDto>里是否有重复的UserInfoDto,不能使用contains 例: List<UserInfoDto> list = new Array ...
- P和C
import tensorflow as tf import numpy as np import math import keras from keras.layers import Conv2D, ...
- 20175314 《Java程序设计》第七周学习总结
20175314 <Java程序设计>第七周学习总结 教材学习内容总结 第八章:常用实用类 String()类代表字符串:Java 程序中的所有字符串字面值(如 "abc&quo ...
- Linux进程的实际用户ID和有效用户ID
转自:https://blog.csdn.net/hulifangjiayou/article/details/47400943 在Linux中,每个文件都有其所属的用户和用户组,默认情况下是文件的创 ...
- Mnist
Mnist 先贴一个介绍的很好的博客 https://blog.csdn.net/sysushui/article/details/53257185 mnist是一个手写体数字的数据集.上图是数据集的 ...
- 在centos7 部署bbr
How to Deploy Google BBR on CentOS 7 Published on: Thu, Jan 5, 2017 at 6:34 pm EST CentOS Linux Guid ...
- 关于egg.js的安全延伸思考
我看到全部的安全基于围绕http来操作,那么如果我只用websocket传输数据,是不是就会好很多?