Spring MVC中核心Servlet繼承圖

核心Servlet繼承圖


XXXAware在 spring中是可以感知的逮京。既XXXAare就是告訴spring队橙,要從其容器中拿到XXX候味。例如ApplicationContextAware中只有一個方法為setApplicationContext(ApplicationContext applicationContext)酷窥。如果需要ApplicationContext泵三,只需要實現(xiàn)ApplicationContext接口中setApplicationContext()方法耕捞。spring會自動調(diào)用setApplicationContext()方法將ApplicationContext傳遞給調(diào)用者。EnvironmentCapable是告訴spring烫幕,有提供Environment的能力俺抽。因此當(dāng)Spring需要Environment的時候只需要實現(xiàn)EnvironmentCapable接口的getEnvironment()方法。

HttpServletBean中的init()方法

/**
     * Map config parameters onto bean properties of this servlet, and
     * invoke subclass initialization.
     * @throws ServletException if bean properties are invalid (or required
     * properties are missing), or if subclass initialization fails.
     */
    @Override
    public final void init() throws ServletException {
        if (logger.isDebugEnabled()) {
           logger.debug("Initializing servlet '" + getServletName() + "'");
        }

        // Set bean properties from init parameters.
        try {
           PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
           BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
           ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
            bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
           initBeanWrapper(bw);
           bw.setPropertyValues(pvs, true);
        }
        catch (BeansException ex) {
           logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
           throw ex;
        }

        // Let subclasses do whatever initialization they like.
        initServletBean();

        if (logger.isDebugEnabled()) {
           logger.debug("Servlet '" + getServletName() + "' configured successfully");
        }
    }

BeanWrapper是spring提供可以去操作javaBean屬性的工具他可以直接修改一個對象屬性的的值较曼。

/**
 *
 * @author cheng
 *
 */
public class User {

    private String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public static void main(String[] args) {
        User user = new User();
        BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(user);
        beanWrapper.setPropertyValue("username", "xiaocheng");
        System.out.println(user.getUsername());

        PropertyValue propertyValue = new PropertyValue("username", "cheng");
        beanWrapper.setPropertyValue(propertyValue);
        System.out.println(user.getUsername());
    }
}

FrameworkServlet 由上面的分析可知Framework的初始化入口為initServletBean

/**
     * Overridden method of {@link HttpServletBean}, invoked after any bean properties
     * have been set. Creates this servlet's WebApplicationContext.
     */
    @Override
    protected final void initServletBean() throws ServletException {
        getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");
        if (this.logger.isInfoEnabled()) {
            this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started");
        }
        long startTime = System.currentTimeMillis();

        try {
           this.webApplicationContext = initWebApplicationContext();
           initFrameworkServlet();
        }
        catch (ServletException ex) {
           this.logger.error("Context initialization failed", ex);
           throw ex;
        }
        catch (RuntimeException ex) {
           this.logger.error("Context initialization failed", ex);
           throw ex;
        }

        if (this.logger.isInfoEnabled()) {
           long elapsedTime = System.currentTimeMillis() - startTime;
            this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " +
                   elapsedTime + " ms");
        }
    }

initWebApplicationContext()方法

/**
     * Initialize and publish the WebApplicationContext for this servlet.
     * <p>Delegates to {@link #createWebApplicationContext} for actual creation
     * of the context. Can be overridden in subclasses.
     * @return the WebApplicationContext instance
     * @see #FrameworkServlet(WebApplicationContext)
     * @see #setContextClass
     * @see #setContextConfigLocation
     */
    protected WebApplicationContext initWebApplicationContext() {
        WebApplicationContext rootContext =
               WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        WebApplicationContext wac = null;

        if (this.webApplicationContext != null) {
           // A context instance was injected at construction time -> use it
           wac = this.webApplicationContext;
           if (wac instanceof ConfigurableWebApplicationContext) {
               ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
               if (!cwac.isActive()) {
                   // The context has not yet been refreshed -> provide services such as
                   // setting the parent context, setting the application context id, etc
                   if (cwac.getParent() == null) {
                       // The context instance was injected without an explicit parent -> set
                       // the root application context (if any; may be null) as the parent
                       cwac.setParent(rootContext);
                   }
                   configureAndRefreshWebApplicationContext(cwac);
               }
           }
        }
        if (wac == null) {
           // No context instance was injected at construction time -> see if one
           // has been registered in the servlet context. If one exists, it is assumed
           // that the parent context (if any) has already been set and that the
           // user has performed any initialization such as setting the context id
           wac = findWebApplicationContext();
        }
        if (wac == null) {
           // No context instance is defined for this servlet -> create a local one
           wac = createWebApplicationContext(rootContext);
        }

        if (!this.refreshEventReceived) {
           // Either the context is not a ConfigurableApplicationContext with refresh
           // support or the context injected at construction time had already been
           // refreshed -> trigger initial onRefresh manually here.
           onRefresh(wac);
        }

        if (this.publishContext) {
           // Publish the context as a servlet context attribute.
           String attrName = getServletContextAttributeName();
            getServletContext().setAttribute(attrName, wac);
           if (this.logger.isDebugEnabled()) {
               this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
                       "' as ServletContext attribute with name [" + attrName + "]");
           }
        }

        return wac;
    }

initWebApplicationContext()主要做了三件事1.獲取spring的根容器rootContext磷斧。2.設(shè)置webApplicationContext并根據(jù)情況調(diào)用onRefresh()方法。3.將webApplicationContext設(shè)置在ServletContext中捷犹。

DispatcherServlet

onRefresh()方法為DispatcherServlet的入口方法弛饭。而onRefresh()方法有直接調(diào)用了initStrategies()方法。

 /**
     * This implementation calls {@link #initStrategies}.
     */
    @Override
    protected void onRefresh(ApplicationContext context) {
        initStrategies(context);
    }

    /**
     * Initialize the strategy objects that this servlet uses.
     * <p>May be overridden in subclasses in order to initialize further strategy objects.
     */
    protected void initStrategies(ApplicationContext context) {
        initMultipartResolver(context);
        initLocaleResolver(context);
        initThemeResolver(context);
        initHandlerMappings(context);
        initHandlerAdapters(context);
        initHandlerExceptionResolvers(context);
        initRequestToViewNameTranslator(context);
        initViewResolvers(context);
        initFlashMapManager(context);
    }

doService()方法

protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
         if (logger.isDebugEnabled()) {
             String resumed = WebAsyncUtils.getAsyncManager(request).hasConcurrentResult() ? " resumed" : "";
             logger.debug("DispatcherServlet with name '" + getServletName() + "'" + resumed +
                     " processing " + request.getMethod() + " request for [" + getRequestUri(request) + "]");
         }

         // Keep a snapshot of the request attributes in case of an include,
         // to be able to restore the original attributes after the include.
         Map<String, Object> attributesSnapshot = null;
         if (WebUtils.isIncludeRequest(request)) {
             attributesSnapshot = new HashMap<String, Object>();
             Enumeration<?> attrNames = request.getAttributeNames();
             while (attrNames.hasMoreElements()) {
                 String attrName = (String) attrNames.nextElement();
                 if (this.cleanupAfterInclude || attrName.startsWith("org.springframework.web.servlet")) {
                     attributesSnapshot.put(attrName, request.getAttribute(attrName));
                 }
             }
         }

         // Make framework objects available to handlers and view objects.
        request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());
        request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
        request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);
        request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());

         FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(request, response);
         if (inputFlashMap != null) {
             request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));
         }
        request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
        request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager);

         try {
             doDispatch(request, response);
         }
         finally {
             if (WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
                 return;
             }
             // Restore the original attribute snapshot, in case of an include.
             if (attributesSnapshot != null) {
                 restoreAttributesAfterInclude(request, attributesSnapshot);
             }
         }
    }

doDispatch()方法

/**
     * Process the actual dispatching to the handler.
     * <p>The handler will be obtained by applying the servlet's HandlerMappings in order.
     * The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters
     * to find the first that supports the handler class.
     * <p>All HTTP methods are handled by this method. It's up to HandlerAdapters or handlers
     * themselves to decide which methods are acceptable.
     * @param request current HTTP request
     * @param response current HTTP response
     * @throws Exception in case of any kind of processing failure
     */
    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 || mappedHandler.getHandler() == 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 (logger.isDebugEnabled()) {
                         logger.debug("Last-Modified value for [" + getRequestUri(request) + "] is: " + lastModified);
                     }
                     if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
                          return;
                     }
                 }

                 if (!mappedHandler.applyPreHandle(processedRequest, response)) {
                     return;
                 }

                 try {
                     // Actually invoke the handler.
                     mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
                 }
                 finally {
                     if (asyncManager.isConcurrentHandlingStarted()) {
                          return;
                     }
                 }

                 applyDefaultViewName(request, mv);
                 mappedHandler.applyPostHandle(processedRequest, response, mv);
             }
             catch (Exception ex) {
                 dispatchException = ex;
             }
             processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
         }
         catch (Exception ex) {
             triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
         }
         catch (Error err) {
             triggerAfterCompletionWithError(processedRequest, response, mappedHandler, err);
         }
         finally {
             if (asyncManager.isConcurrentHandlingStarted()) {
                 // Instead of postHandle and afterCompletion
                 mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
                 return;
             }
             // Clean up any resources used by a multipart request.
             if (multipartRequestParsed) {
                 cleanupMultipart(processedRequest);
             }
         }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子负敏,更是在濱河造成了極大的恐慌今穿,老刑警劉巖,帶你破解...
    沈念sama閱讀 223,207評論 6 521
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件伶丐,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機拒担,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,455評論 3 400
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來攻询,“玉大人从撼,你說我怎么就攤上這事【埽” “怎么了低零?”我有些...
    開封第一講書人閱讀 170,031評論 0 366
  • 文/不壞的土叔 我叫張陵,是天一觀的道長拯杠。 經(jīng)常有香客問我毁兆,道長,這世上最難降的妖魔是什么阴挣? 我笑而不...
    開封第一講書人閱讀 60,334評論 1 300
  • 正文 為了忘掉前任气堕,我火速辦了婚禮,結(jié)果婚禮上畔咧,老公的妹妹穿的比我還像新娘茎芭。我一直安慰自己,他們只是感情好誓沸,可當(dāng)我...
    茶點故事閱讀 69,322評論 6 398
  • 文/花漫 我一把揭開白布梅桩。 她就那樣靜靜地躺著,像睡著了一般拜隧。 火紅的嫁衣襯著肌膚如雪宿百。 梳的紋絲不亂的頭發(fā)上趁仙,一...
    開封第一講書人閱讀 52,895評論 1 314
  • 那天,我揣著相機與錄音垦页,去河邊找鬼雀费。 笑死,一個胖子當(dāng)著我的面吹牛痊焊,可吹牛的內(nèi)容都是我干的盏袄。 我是一名探鬼主播,決...
    沈念sama閱讀 41,300評論 3 424
  • 文/蒼蘭香墨 我猛地睜開眼薄啥,長吁一口氣:“原來是場噩夢啊……” “哼辕羽!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起垄惧,我...
    開封第一講書人閱讀 40,264評論 0 277
  • 序言:老撾萬榮一對情侶失蹤刁愿,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后到逊,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體酌毡,經(jīng)...
    沈念sama閱讀 46,784評論 1 321
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,870評論 3 343
  • 正文 我和宋清朗相戀三年蕾管,在試婚紗的時候發(fā)現(xiàn)自己被綠了枷踏。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,989評論 1 354
  • 序言:一個原本活蹦亂跳的男人離奇死亡掰曾,死狀恐怖旭蠕,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情旷坦,我是刑警寧澤掏熬,帶...
    沈念sama閱讀 36,649評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站秒梅,受9級特大地震影響旗芬,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜捆蜀,卻給世界環(huán)境...
    茶點故事閱讀 42,331評論 3 336
  • 文/蒙蒙 一疮丛、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧辆它,春花似錦誊薄、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,814評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至飒筑,卻和暖如春片吊,著一層夾襖步出監(jiān)牢的瞬間绽昏,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,940評論 1 275
  • 我被黑心中介騙來泰國打工俏脊, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留全谤,地道東北人。 一個月前我還...
    沈念sama閱讀 49,452評論 3 379
  • 正文 我出身青樓联予,卻偏偏與公主長得像啼县,于是被迫代替她去往敵國和親材原。 傳聞我的和親對象是個殘疾皇子沸久,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,995評論 2 361

推薦閱讀更多精彩內(nèi)容

  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,871評論 6 342
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn)余蟹,斷路器卷胯,智...
    卡卡羅2017閱讀 134,722評論 18 139
  • IOC 控制反轉(zhuǎn),用一句話解釋這個概念就是將對象的創(chuàng)建和獲取提取到外部威酒。由外部容器提供需要的組件窑睁。 AOP 確實就...
    HeartGo閱讀 1,039評論 0 3
  • 什么是Spring Spring是一個開源的Java EE開發(fā)框架。Spring框架的核心功能可以應(yīng)用在任何Jav...
    jemmm閱讀 16,475評論 1 133