SpringMVC核心就是DispatcherServlet,全部得請求都會轉發到DispatcherServlet,而後再經過DispatcherServlet執行具體得控制層(Handler)返回ModelAndView給客戶端視圖展現。web
// 3. 將咱們的DispatcherServlet 注入到 serlvet容器中 ServletRegistration.Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(app)); // 4.填寫url路徑映射 dynamic.addMapping("/");
DispatcherServlet其實就是一個Servlet類,無非就是包裝一層,經過url可以映射找到咱們得SpringMvc中定義得請求方法。app
源代碼分析:編輯器
DispatcherServlet繼承FrameworkServlet繼承HttpServletide
面向基本上思想 重寫 先走父類 ,在走子類。函數
得出答案:先看HttpServlet在找到咱們最後的子類源碼分析
protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.processRequest(request, response);
}
關係:DispatcherServlet繼承FrameworkServlet繼承HttpServletpost
流程執行關係:ui
HttpServlet service方法 判斷請求方法的類型this
FrameworkServlet doServiceurl
DispatcherServlet doService
在servlet初始化階段會調用其init方法,因此咱們首先要查看在DispatcherServlet中是否重寫了init方法。咱們在其父類HttpServletBean中找到該方法
public abstract class HttpServletBean extends HttpServlet implements EnvironmentCapable, EnvironmentAware { .... public final void init() throws ServletException { if (this.logger.isDebugEnabled()) { this.logger.debug("Initializing servlet '" + this.getServletName() + "'"); } //解析init-param並封裝至pvs中 PropertyValues pvs = new HttpServletBean.ServletConfigPropertyValues(this.getServletConfig(), this.requiredProperties); if (!pvs.isEmpty()) { try { //將當前的servlet類轉換爲一個BeanWrapper,從而可以以Spring的方式來對init-param的值進行注入 BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this); ResourceLoader resourceLoader = new ServletContextResourceLoader(this.getServletContext()); //註冊自定義屬性編輯器,一旦遇到Resource類型的屬性會使用ResourceEditor進行解析 bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, this.getEnvironment())); //空實現,留給子類覆蓋 this.initBeanWrapper(bw); //屬性注入 bw.setPropertyValues(pvs, true); } catch (BeansException var4) { if (this.logger.isErrorEnabled()) { this.logger.error("Failed to set bean properties on servlet '" + this.getServletName() + "'", var4); } throw var4; } } //留給子類擴展 this.initServletBean(); if (this.logger.isDebugEnabled()) { this.logger.debug("Servlet '" + this.getServletName() + "' configured successfully"); } } .... }
DispatcherServlet的初始化過程主要是經過將當前的Servlet類型實例轉換爲BeanWrapper類型實例,以便使用Spring中提供的注入功能進行對應屬性的注入。
咱們看下servletBean的初始化,HttpServletBean其父類FrameworkServlet覆蓋了它的initServletBean函數,以下:
protected final void initServletBean() throws ServletException { this.getServletContext().log("Initializing Spring FrameworkServlet '" + this.getServletName() + "'"); if (this.logger.isInfoEnabled()) { this.logger.info("FrameworkServlet '" + this.getServletName() + "': initialization started"); } //計時器,統計初始化的執行時間 long startTime = System.currentTimeMillis(); try { //關鍵的初始化邏輯委託給了這個方法 this.webApplicationContext = this.initWebApplicationContext(); //設計爲子類覆蓋 this.initFrameworkServlet(); } catch (RuntimeException | ServletException var5) { this.logger.error("Context initialization failed", var5); throw var5; } if (this.logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - startTime; this.logger.info("FrameworkServlet '" + this.getServletName() + "': initialization completed in " + elapsedTime + " ms"); } }
initWebApplicationContext函數主要工做就是建立或者刷新WebApplicationContext 實例並對servlet功能所使用的變量進行初始化
protected WebApplicationContext initWebApplicationContext() { WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); WebApplicationContext wac = null; if (this.webApplicationContext != null) { //context實例在構造函數中被注入 wac = this.webApplicationContext; if (wac instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext)wac; if (!cwac.isActive()) { if (cwac.getParent() == null) { cwac.setParent(rootContext); } //刷新上下文環境 this.configureAndRefreshWebApplicationContext(cwac); } } } if (wac == null) { //根據contextAttribute屬性加載webApplicationContext wac = this.findWebApplicationContext(); } if (wac == null) { wac = this.createWebApplicationContext(rootContext); } if (!this.refreshEventReceived) { this.onRefresh(wac); } if (this.publishContext) { String attrName = this.getServletContextAttributeName(); this.getServletContext().setAttribute(attrName, wac); if (this.logger.isDebugEnabled()) { this.logger.debug("Published WebApplicationContext of servlet '" + this.getServletName() + "' as ServletContext attribute with name [" + attrName + "]"); } } return wac; }
刷新方法onRefresh
protected void onRefresh(ApplicationContext context) {
this.initStrategies(context);
}
protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context); //初始化上傳文件解析器(或者是多部分請求解析器)
initLocaleResolver(context);//初始化本地化解析器
initThemeResolver(context);//初始化主題解析器
initHandlerMappings(context);//初始化處理器映射器
initHandlerAdapters(context);//初始化處理器適配器
initHandlerExceptionResolvers(context);//初始化處理器異常解析器
initRequestToViewNameTranslator(context);//初始化請求到視圖名翻譯器
initViewResolvers(context);//初始化視圖解析器
initFlashMapManager(context);//初始化重定向數據管理器
}
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
...
try {
try {
...
//經過url路徑地址去查找控制層類方法,若是沒有找到的化,直接返回404
mappedHandler = this.getHandler(processedRequest);
....
HandlerAdapter ha = this.getHandlerAdapter(mappedHandler.getHandler());
String method = request.getMethod();
boolean isGet = "GET".equals(method);
....
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
....
mappedHandler.applyPostHandle(processedRequest, response, mv);
....
}
private List<HandlerMapping> handlerMappings;
mappedHandler = this.getHandler(processedRequest);
HandlerAdapter ha = this.getHandlerAdapter(mappedHandler.getHandler());
if (!mappedHandler.applyPreHandle(processedRequest, response)) { return; }
/** * 請求方法前置攔截,若是返回true 表示會執行到目標方法(請求方法) 若是返回false的狀況下 則不會執行目標方法。 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String token = request.getParameter("token"); System.out.println(">>>>token<<<<:" + token); if (StringUtils.isEmpty(token)) { response.setStatus(500); response.getWriter().print(" token is null"); return false; } // 執行咱們的請求方法 return true; }
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
執行目標方法:
@RequestMapping("/pageIndex") public String pageIndex() { System.out.println(">>>pageIndex<<<<"); return "pageIndex"; }
mappedHandler.applyPostHandle(processedRequest, response, mv);
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("<<<postHandle>>>>");
// 請求以後執行。
}
1.執行doDispatch
2.調用getHandler方法獲取請求目標的方法 也就是 請求url映射路徑對應的控制層具體的方法
handlerMappings的做用查找控制器位置,好比xml和註解方式。
3.調用getHandlerAdapter獲取控制層適配器 RequestMappingHandlerAdapter
4.執行攔截器前置方法 preHandle() 若是返回爲true的話
5.執行實際請求目標方法 返回modeAndView對象
6.執行攔截器PostHandle()方法
7.設置渲染視圖層內容
8.執行攔截器afterCompletion方
SpringMVC控制層容器初始化
- HttpServletBean init ()方法
- FrameworkServlet initServletBean方法→ initWebApplicationContext();
- DispatcherServlet onRefresh方法→ initStrategies()方法
protected void onRefresh(ApplicationContext context) {
this.initStrategies(context);
}
當咱們servlet容器初始化的時候初始化
this.initHandlerMappings(context);
本文參考
參考數據:Spring源碼深度解析
螞蟻課堂