HandlerAdapter字面上的意思就是處理適配器,它的作用用一句話概括就是調用具體的方法對使用者發來的請求來進行處理。當handlerMapping擷取到執行請求的controller時,DispatcherServlte會根據controller對應的controller類型來調用相應的HandlerAdapter來進行處理。
在貼源碼之前先說一下HandlerAdapter處理的大體流程,這樣就有一個大體的掌握。大體流程有三步:
1.DispatcherServlte會根據設定檔資訊註冊HandlerAdapter,如果在設定檔中沒有配置,那麼DispatcherServlte會擷取HandlerAdapter的預設配置,如果是讀取預設配置的話,DispatcherServlte會讀取DispatcherServlte.properties檔案,該檔案中配置了三種HandlerAdapter:HttpRequestHandlerAdapter,SimpleControllerHandlerAdapter和AnnotationMethodHandlerAdapter。DispatcherServlte會將這三個HandlerAdapterObject Storage Service到它的handlerAdapters這個集合屬性中,這樣就完成了HandlerAdapter的註冊。
2.DispatcherServlte會根據handlerMapping傳過來的controller與已經註冊好了的HandlerAdapter一一匹配,看哪一種HandlerAdapter是支援該controller類型的,如果找到了其中一種HandlerAdapter是支援傳過來的controller類型,那麼該HandlerAdapter會調用自己的handle方法,handle方法運用Java的反射機制執行controller的具體方法來獲得ModelAndView,例如SimpleControllerHandlerAdapter是支援實現了controller介面的控制器,如果自己寫的控制器實現了controller介面,那麼SimpleControllerHandlerAdapter就會去執行自己寫控制器中的具體方法來完成請求。
下面是我自己寫的代碼。
1.自己寫的controller,就是我們自己寫的控制器
[java] view plain copy package com.wangbiao.springMVC; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; public class HelloWorld extends MultiActionController{ public ModelAndView sayHelloWorld(HttpServletRequest request, HttpServletResponse response) { String param = request.getParameter("param"); System.out.println("springMVC測試:helloWorld;"+param); ModelAndView mv = new ModelAndView(); mv.addObject("content", "springMVC HelloWorld:"+param); mv.setViewName("springMVC/helloWorld"); ServletContext ctx = this.getServletContext(); return mv; } }
2.SpringMVC設定檔
[java] view plain copy <?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http: