Spring MVC中核心Servlet继承图

核心Servlet继承图


XXXAware在 spring中是可以感知的。既XXXAare就是告诉spring,要从其容器中拿到XXX。例如ApplicationContextAware中只有一个方法为setApplicationContext(ApplicationContext applicationContext)。如果需要ApplicationContext,只需要实现ApplicationContext接口中setApplicationContext()方法。spring会自动调用setApplicationContext()方法将ApplicationContext传递给调用者。EnvironmentCapable是告诉spring,有提供Environment的能力。因此当Spring需要Environment的时候只需要实现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.设置webApplicationContext并根据情况调用onRefresh()方法。3.将webApplicationContext设置在ServletContext中。

DispatcherServlet

onRefresh()方法为DispatcherServlet的入口方法。而onRefresh()方法有直接调用了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);
             }
         }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,445评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,889评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,047评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,760评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,745评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,638评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,011评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,669评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,923评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,655评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,740评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,406评论 4 320
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,995评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,961评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,023评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,483评论 2 342

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,733评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,594评论 18 139
  • IOC 控制反转,用一句话解释这个概念就是将对象的创建和获取提取到外部。由外部容器提供需要的组件。 AOP 确实就...
    HeartGo阅读 1,032评论 0 3
  • 什么是Spring Spring是一个开源的Java EE开发框架。Spring框架的核心功能可以应用在任何Jav...
    jemmm阅读 16,438评论 1 133