一、什么是HandlerAdapter

Note that a handler can be of type Object. This is to enable handlers from other frameworks to be integrated with this framework without custom coding.

boolean supports(Object handler)

Given a handler instance, return whether or not this HandlerAdapter can support it.

HandlerAdapter 接口实现类:

1. HttpRequestHandlerAdapter : 要求handler实现HttpRequestHandler接口

public class HttpRequestHandlerAdapter implements HandlerAdapter {

    @Override
public boolean supports(Object handler) {
return (handler instanceof HttpRequestHandler);
} @Override
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception { ((HttpRequestHandler) handler).handleRequest(request, response);
return null;
} @Override
public long getLastModified(HttpServletRequest request, Object handler) {
if (handler instanceof LastModified) {
return ((LastModified) handler).getLastModified(request);
}
return -1L;
} }

2. SimpleControllerHandlerAdapter:要求handler实现Controller接口,该接口的方法参数为ModelAndView

public class SimpleControllerHandlerAdapter implements HandlerAdapter {

    @Override
public boolean supports(Object handler) {
return (handler instanceof Controller);
} @Override
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception { return ((Controller) handler).handleRequest(request, response);
} @Override
public long getLastModified(HttpServletRequest request, Object handler) {
if (handler instanceof LastModified) {
return ((LastModified) handler).getLastModified(request);
}
return -1L;
} }

3. AbstracthandlerMethodAdapter的handle()使用模板方法,调用子类handleInternal()实现

    @Override
public final boolean supports(Object handler) {
return (handler instanceof HandlerMethod && supportsInternal((HandlerMethod) handler));
} protected abstract boolean supportsInternal(HandlerMethod handlerMethod); @Override
public final ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception { return handleInternal(request, response, (HandlerMethod) handler);
} protected abstract ModelAndView handleInternal(HttpServletRequest request,
HttpServletResponse response, HandlerMethod handlerMethod) throws Exception;

AbstracthandlerMethodAdapter及其子类RequestMappingHandlerAdapter的supportsInternal()方法

    /**
* Always return {@code true} since any method argument and return value
* type will be processed in some way. A method argument not recognized
* by any HandlerMethodArgumentResolver is interpreted as a request parameter
* if it is a simple type, or as a model attribute otherwise. A return value
* not recognized by any HandlerMethodReturnValueHandler will be interpreted
* as a model attribute.
*/
@Override
protected boolean supportsInternal(HandlerMethod handlerMethod) {
return true;
}

二、什么是HandlerMethod:封装了请求处理方法的参数和返回值,及该方法上的注解

Encapsulates information about a handler method consisting of a method and a bean. Provides convenient access to method parameters, the method return value, method annotations, etc.

The class may be created with a bean instance or with a bean name (e.g. lazy-init bean, prototype bean).

Use createWithResolvedBean() to obtain a HandlerMethod instance with a bean instance resolved through the associated BeanFactory.

三、什么时候使用HandlerAdapter

1. DispatchServlet protected void doDispatch()方法会获取相应的HandlerAdapter

                // Determine handler adapter for the current request.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

在以前的文章中,已经说过RequestMappingHandlerAdapter是处理输入输出的关键点,也是spring根据相应的路径查找对应的处理器的关键点

RequestMappingHandlerAdapter的handleInternal()会调用invokeHandlerMethod()

    protected ModelAndView invokeHandlerMethod(HttpServletRequest request,
HttpServletResponse response, HandlerMethod handlerMethod) throws Exception { ServletWebRequest webRequest = new ServletWebRequest(request, response);
try {
WebDataBinderFactory binderFactory = getDataBinderFactory(handlerMethod);
ModelFactory modelFactory = getModelFactory(handlerMethod, binderFactory);
        //创建ServletInvocableHandlerMethod
ServletInvocableHandlerMethod invocableMethod = createInvocableHandlerMethod(handlerMethod);
invocableMethod.setHandlerMethodArgumentResolvers(this.argumentResolvers);
invocableMethod.setHandlerMethodReturnValueHandlers(this.returnValueHandlers);
invocableMethod.setDataBinderFactory(binderFactory);
invocableMethod.setParameterNameDiscoverer(this.parameterNameDiscoverer); ModelAndViewContainer mavContainer = new ModelAndViewContainer();
mavContainer.addAllAttributes(RequestContextUtils.getInputFlashMap(request));
modelFactory.initModel(webRequest, mavContainer, invocableMethod);
mavContainer.setIgnoreDefaultModelOnRedirect(this.ignoreDefaultModelOnRedirect); AsyncWebRequest asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response);
asyncWebRequest.setTimeout(this.asyncRequestTimeout); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
asyncManager.setTaskExecutor(this.taskExecutor);
asyncManager.setAsyncWebRequest(asyncWebRequest);
asyncManager.registerCallableInterceptors(this.callableInterceptors);
asyncManager.registerDeferredResultInterceptors(this.deferredResultInterceptors); if (asyncManager.hasConcurrentResult()) {
Object result = asyncManager.getConcurrentResult();
mavContainer = (ModelAndViewContainer) asyncManager.getConcurrentResultContext()[0];
asyncManager.clearConcurrentResult();
if (logger.isDebugEnabled()) {
logger.debug("Found concurrent result value [" + result + "]");
}
invocableMethod = invocableMethod.wrapConcurrentResult(result);
}
//调用
invocableMethod.invokeAndHandle(webRequest, mavContainer);
if (asyncManager.isConcurrentHandlingStarted()) {
return null;
} return getModelAndView(mavContainer, modelFactory, webRequest);
}
finally {
webRequest.requestCompleted();
}
}

3.一个请求过来时,InvocableHandlerMethod的执行变量

从上面的分析看到,处理请求时,会调用invokeAndHandle(),最终是doInvoke执行

4.  疑问:这些HandlerMethond是什么时候载入系统的

解答:系统启动的时候执行registerHandlerMethod()方法,创建HandlerMethod实例

三、HandlerMapping VS HandlerAdapter

The strategy interface HandlerAdapter takes the role of invoking handler methods selected by some HandlerMapping.

SpringMVC(四):什么是HandlerAdapter的更多相关文章

  1. SpringMVC源码解析- HandlerAdapter - ModelFactory(转)

    ModelFactory主要是两个职责: 1. 初始化model 2. 处理器执行后将modle中相应参数设置到SessionAttributes中 我们来看看具体的处理逻辑(直接充当分析目录): 1 ...

  2. SpringMVC源码解析- HandlerAdapter - ModelFactory

    ModelFactory主要是两个职责: 1. 初始化model 2. 处理器执行后将modle中相应参数设置到SessionAttributes中 我们来看看具体的处理逻辑(直接充当分析目录): 1 ...

  3. springMVC源码分析--HandlerAdapter(一)

    HandlerAdapter的功能实际就是执行我们的具体的Controller.Servlet或者HttpRequestHandler中的方法. 类结构如下:

  4. Spring MVC源码分析(三):SpringMVC的HandlerMapping和HandlerAdapter的体系结构设计与实现

    概述在我的上一篇文章:Spring源码分析(三):DispatcherServlet的设计与实现中提到,DispatcherServlet在接收到客户端请求时,会遍历DispatcherServlet ...

  5. springmvc(四) springmvc的数据校验的实现

    so easy~ --WH 一.什么是数据校验? 这个比较好理解,就是用来验证客户输入的数据是否合法,比如客户登录时,用户名不能为空,或者不能超出指定长度等要求,这就叫做数据校验. 数据校验分为客户端 ...

  6. SpringMVC(四):@RequestMapping结合org.springframework.web.filter.HiddenHttpMethodFilter实现REST请求

    1)REST具体表现: --- /account/1  HTTP GET       获取id=1的account --- /account/1  HTTP DELETE 删除id=1的account ...

  7. SpringMVC(四) RequestMapping请求方式

    常见的Rest API的Get和POST的测试参考代码如下,其中web.xml和Springmvc的配置文件参考HelloWorld测试代码中的配置. 控制类的代码如下: package com.ti ...

  8. SSM-SpringMVC-17:SpringMVC中深度剖析HandlerAdapter处理器适配器底层

     ------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 先放一张图 很熟悉啊,之前就看过,我们之前已经把handlerMapping剖了个底朝天,顺着上次的进度,继 ...

  9. SpringMVC源码解析 - HandlerAdapter - @SessionAttributes注解处理

    使用SpringMVC开发时,可以使用@SessionAttributes注解缓存信息.这样业务开发时,就不需要一次次手动操作session保存,读数据. @Controller @RequestMa ...

随机推荐

  1. MySql 建表、添加字段、修改字段、添加索引SQL语句写法及SQL索引

    ---------添加索引方法--------- .添加PRIMARY KEY(主键索引) mysql>ALTER TABLE `table_name` ADD PRIMARY KEY ( `c ...

  2. 【Vegas原创】SQLServer2008防小人利器:审核/审计功能

    小人见怪不怪,世界上最可怕的就是会技术的小人,防不胜防! sa密码泄露也就算了,关键是人家也可以前台攻击,直接把你弄的没辙! 在诅咒这种小人的同时,除了加强服务器安全管理,密码策略等,SQL Serv ...

  3. Atitit r2017 r6 doc list on home ntpc.docx

    Atitit r2017 r6 doc list on home ntpc.docx 驱动器 D 中的卷是 p2soft 卷的序列号是 9AD0-D3C8 D:\ati\r2017 v4 raf\r2 ...

  4. 用xcode9编译出ios越狱机程序使用的dylib

    因为xcode9默认不能创建dylib工程,所以 选择 静态库 工程后,修改编译选项使得变成dylib工程. 步骤: 一.xcode9 -> File -> New -> Proje ...

  5. 你可能不知道的IDEA高级调试技巧

    一.条件断点 循环中经常用到这个技巧,比如:遍历1个大List的过程中,想让断点停在某个特定值. 参考上图,在断点的位置,右击断点旁边的小红点,会出来一个界面,在Condition这里填入断点条件即可 ...

  6. case when then 中判断null的方法

    --下列SQL无效 SELECT CASE MAX(T.CREATE_TIME) WHEN NULL THEN TO_DATE('2019-03-05 00:00:01','yyyy-MM-dd hh ...

  7. C#学习笔记(35)——事件做的登录案例

    说明(2018-4-9 20:11:42): 1. 先自定义了一个登录控件,可以输入账号.密码,点击登录.然后在Form1里面拖入这个控件,要求输入账号密码正确时,点击登录,控件显示绿色,否则显示红色 ...

  8. HTTP 04 web 服务器

    用单台虚拟主机实现多个域名 HTTP/1.1 允许一台 HTTP 服务器搭建多个 web 站点, 例如提供 web 托管服务的供应商, 可以用一台服务器为多位客户服务, 也可以以每位客户持有的域名运行 ...

  9. mybatis打印完整的sql

    mybatis log plugin

  10. Linux 特殊字符_008

    Linux 特殊字符用于用户命令行bash环境处理数据,达到一种命令简化使用的功能 通配符 符号 功能 备注 * 代表所有(0到多个)字符 ? 代表任意一个字符 [ ] 匹配[ ]任意一个字符,写法[ ...