HandlerAdapter的功能實際就是執行我們的具體的Controller、Servlet或者HttpRequestHandler中的方法。
類結構如下:
1、SimpleServletHandlerAdapter實際就是執行HttpServlet的service方法 springMVC源碼分析--SimpleServletHandlerAdapter(二)
2、SimpleControllerHandlerAdapter實際就是執行Controller的handleRequest方法 springMVC源碼分析--SimpleControllerHandlerAdapter(三)
3、HttpRequestHandlerAdapter實際就是執行HttpRequestHandler的handleRequest方法 springMVC源碼分析--HttpRequestHandlerAdapter(四)
4、RequestMappingHandlerAdapter實際就是執行@RequestMapping注解的方法。
5、AnnotationMethodHandlerAdapter已結被廢棄,就不做過多介紹
HandlerAdapter的接口中定義了三個方法:
(1)boolean supports(Object handler); 判斷是否支援傳入的Handler
(2)ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) 用來使用Handler處理請求
(3)long getLastModified(HttpServletRequest request, Object handler); 用來擷取資料的Last-Modified值。
接口源碼如下:
public interface HandlerAdapter {
boolean supports(Object handler);
ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;
long getLastModified(HttpServletRequest request, Object handler);
}
HandlerAdapter的執行操作,其執行過程在DispatcherServlet的doDispatch中,執行流程如下:
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
........
try {
try {
//擷取合适的HandlerAdapter實作類
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
........
if (isGet || "HEAD".equals(method)) {
long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
}
........
//執行真正的請求操作
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
........
}
getHandlerAdapter的操作就是選擇合适的HandlerAdapter來執行,設計模式中的擴充卡模式,handlerAdapters中的内容就是所有的HandlerAdapter的實作類。
protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
for (HandlerAdapter ha : this.handlerAdapters) {
if (logger.isTraceEnabled()) {
logger.trace("Testing handler adapter [" + ha + "]");
}
if (ha.supports(handler)) {
return ha;
}
}
throw new ServletException("No adapter for handler [" + handler +
"]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
}