浅谈SpringMVC请求映射handler源码解读
作者:是冯吉荣呀 发布时间:2022-09-11 14:37:36
请求映射源码
首先看一张请求完整流转图(这里感谢博客园上这位大神的图,博客地址我忘记了):
前台发送给后台的访问请求是如何找到对应的控制器映射并执行后续的后台操作呢,其核心为DispatcherServlet.java与HandlerMapper。在spring boot初始化的时候,将会加载所有的请求与对应的处理器映射为HandlerMapper组件。我们可以在springMVC的自动配置类中找到对应的Bean。
@Bean
@Primary
@Override
public RequestMappingHandlerMapping requestMappingHandlerMapping(
@Qualifier("mvcContentNegotiationManager") ContentNegotiationManager contentNegotiationManager,
@Qualifier("mvcConversionService") FormattingConversionService conversionService,
@Qualifier("mvcResourceUrlProvider") ResourceUrlProvider resourceUrlProvider) {
// Must be @Primary for MvcUriComponentsBuilder to work
return super.requestMappingHandlerMapping(contentNegotiationManager, conversionService,
resourceUrlProvider);
}
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
this.mvcProperties.getStaticPathPattern());
welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
return welcomePageHandlerMapping;
}
请求将首先执行FrameworkServlet
下的service方法根据request请求的method找到对应的do**方法。
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpMethod httpMethod = HttpMethod.resolve(request.getMethod());
if (httpMethod == HttpMethod.PATCH || httpMethod == null) {
processRequest(request, response);
}
else {
//父类根据method参数执行doGet,doPost,doDelete等
super.service(request, response);
}
}
而这些do**其都会进入核心方法,以doGet为例。
@Overrideprotected
final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//核心方法
processRequest(request, response);
}
protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//进入此核心方法
doService(request, response);
}
catch (ServletException | IOException ex) {
failureCause = ex;
throw ex;
}
catch (Throwable ex) {
failureCause = ex;
throw new NestedServletException("Request processing failed", ex);
}
finally {
resetContextHolders(request, previousLocaleContext, previousAttributes);
if (requestAttributes != null) {
requestAttributes.requestCompleted();
}
logResult(request, response, failureCause, asyncManager);
publishRequestHandledEvent(request, response, startTime, failureCause);
}
processRequest()
方法中重点在doService(request, response);
,而其核心处理逻辑位于DispatchServletl类重写的方法,如下。
@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
····
try {
//这里为实际分发控制器的逻辑,其内部是找到对应的handlerMapper
doDispatch(request, response);
}
finally {
if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
// Restore the original attribute snapshot, in case of an include.
if (attributesSnapshot != null) {
restoreAttributesAfterInclude(request, attributesSnapshot);
}
}
if (requestPath != null) {
ServletRequestPathUtils.clearParsedRequestPath(request);
}
}
}
接下来看分发处理逻辑方法,其中重要的方法都使用了原生的注释。接下来分别分析核心源码。
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
boolean multipartRequestParsed = false;
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
try {
ModelAndView mv = null;
Exception dispatchException = null;
try {
processedRequest = checkMultipart(request);
multipartRequestParsed = (processedRequest != request);
// Determine handler for the current request.
mappedHandler = getHandler(processedRequest);
if (mappedHandler == null) {
noHandlerFound(processedRequest, response);
return;
}
// Determine handler adapter for the current request.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
// Process last-modified header, if supported by the handler.
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;
}
// Actually invoke the handler.
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
if (asyncManager.isConcurrentHandlingStarted()) {
return;
}
applyDefaultViewName(processedRequest, mv);
mappedHandler.applyPostHandle(processedRequest, response, mv);
}
catch (Exception ex) {
dispatchException = ex;
}
catch (Throwable err) {
// As of 4.3, we're processing Errors thrown from handler methods as well,
// making them available for @ExceptionHandler methods and other scenarios.
dispatchException = new NestedServletException("Handler dispatch failed", err);
}
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
catch (Exception ex) {
triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
}
catch (Throwable err) {
triggerAfterCompletion(processedRequest, response, mappedHandler,
new NestedServletException("Handler processing failed", err));
}
finally {
if (asyncManager.isConcurrentHandlingStarted()) {
// Instead of postHandle and afterCompletion
if (mappedHandler != null) {
mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
}
}
else {
// Clean up any resources used by a multipart request.
if (multipartRequestParsed) {
cleanupMultipart(processedRequest);
}
}
}
}
首先是分析getHandler(),找到对应的处理器映射逻辑。
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
if (this.handlerMappings != null) {
for (HandlerMapping mapping : this.handlerMappings) {
HandlerExecutionChain handler = mapping.getHandler(request);
if (handler != null) {
return handler;
}
}
}
return null;
}
我们将断点标记在getHandler
方法上时,可以清除看到handlerMappings
,如图。
这里,用户请求与处理器的映射关系都在RequestMapperHandlerMapping
中,而欢迎页处理请求则在WelcomePageHanderMapping
中进行映射。
以下为RequestMapperHandlerMapping中映射部分截图,可以看到用户的所有请求映射这里面都有:
getHandler()后的方法是通过比较request请求中method与HandlerMapper中相同url下的method,再进行唯一性校验,不通过异常,通过找到唯一的handler。
后续,通过handler找到处理的设配器,通过适配器得到一个ModelAndView对象,这个对象就是最后返回给前端页面的对象。
至此,一个请求完整映射到返回前端结束。
说明:这是实现了FramworkServlet的doService方法,FramworkServlet继承自HttpServlet,并且重写了父类中的doGet(),doPost(),doPut(),doDelete 等方法,在这些重写的方法里都调用了 processRquest() 方法做请求处理,进入processRquest()可以看到里面调用了FramworkServlet中定义的doService() 方法。
来源:https://www.cnblogs.com/fjrgg/p/14545387.html
猜你喜欢
- 写在前面:接下来很长一段时间的文章主要会记录一些项目中实际遇到的问题及对应的解决方案,在相应代码分析时会直指问题所在,不会将无关的流程代码贴
- 本文实例讲述了Spring的组合注解和元注解原理与用法。分享给大家供大家参考,具体如下:一 点睛从Spring 2开始,为了相应JDK 1.
- 前言由于android M的popupwindow与之前版本不一致,笔者找不到能够代码监听物理返回键的方式,故另寻方式实现筛选菜单。5.0及
- 下面是一个AOP实现的简单例子:首先定义一些业务方法:/** * Created with IntelliJ IDEA. 
- 本文为大家分享了Unity制作签名功能的具体代码,供大家参考,具体内容如下前言:项目中需要做一个签名的功能,同时需要两个两个屏幕进行显示,但
- A:首先先看下一个简单的面试题斐波那契数列计算数组{1,1,2,3,5,8.......} 第30位值规律:1 1 从第三项开始,每一项都是
- 参数和返回值得加密目的为了保证接口不被人拦截下来恶意请求,保证程序的稳定性,我们可以使用接口加密的方法来保证参数和返回值的保密性。具体实现方
- 1.新建一个数组,把原来数组的内容搬到新数组中。这种方法实现的思路是:先新建一个数组(前提条件是长度得比原来的长),然后把原来数组的内容搬到
- 以下内容通过1、实现目标注入程序,2、实现主程序,3、实现注入函数,4、thumb指令集实现等4个方面详细分析了android中inline
- 为什么要用synchronized相信大家对于这个问题一定都有自己的答案,这里我还是要啰嗦一下,我们来看下面这段车站售票的代码:/** *
- Mybatis 复杂对象resultMap数据对象含有普通属性,一对一对象,一对多对象(2种情况:单一主键和复合主键)下面是resultMa
- 有时候我们需要在一个ArrayList的for循环中动态删除元素的需求, 废话不多说看代码List<Integer> list
- 在前面的内容已经学会了如何定义变量和初始化变量。定义变量的目的就是为了操作数据。Java 语言中给我们提供了专门用来操作这些数据的代码符号,
- 一、前言最近接到一个任务,需要爬取五级行政区划的所有数据(大概71万条数据在),需要爬取的网站:行政区划 - 行政区划代码查询 发
- 本文实例讲述了C#监控文件夹变化的方法。分享给大家供大家参考。具体实现方法如下:当需要监控某一文件,FileSystemWatcher类提供
- 一、委托1、什么是委托委托是面向对象的、类型安全的,是引用类型。使用delegate关键字进行定义。委托的本质就是一个类,继承自System
- spring-task定时任务动态配置修改执行时间因项目需要,几个定时任务需要人为动态设置执行时间,于是乎吧,就查阅相关资料,是可以动态设置
- 基本用法不说了,网上例子很多,这里主要介绍下比较特殊情况下使用的方法。1. 分组有的时候,我们对一个实体类需要有多中验证方式,在不同的情况下
- 本文实例为大家分享了java实现加减乘除计算器的具体代码,供大家参考,具体内容如下代码import java.awt.*;import ja
- 本文实例讲述了Android开发实现拨打电话与发送信息的方法。分享给大家供大家参考,具体如下:xml布局:<LinearLayout