zoukankan      html  css  js  c++  java
  • spring mvc源码解析

    1.从DispatcherServlet开始
         与很多使用广泛的MVC框架一样,SpringMVC使用的是FrontController模式,所有的设计都围绕DispatcherServlet 为中心来展开的。见下图,所有请求从DispatcherServlet进入,DispatcherServlet根据配置好的映射策略确定处理的 Controller,Controller处理完成返回ModelAndView,DispatcherServlet根据配置好的视图策略确定处理的 View,由View生成具体的视图返回给请求客户端。


    2.初始化
        SpringMVC几个核心的配置策略包括:
        *HandlerMapping:请求-处理器映射策略处理,根据请求生成具体的处理链对象
        *HandlerAdapter:处理器适配器,由于最终的Handler对象不一定是一个标准接口的实现对象,参数也可能非常的灵活复杂,因此所有的对象需要一个合适的适配器适配成标准的处理接口来最终执行请求
        *ViewResolver:视图映射策略,根据视图名称和请求情况,最终映射到具体的处理View,由View对象来生成具体的视图。
        其他的配置策略包括MultipartResolver、LocaleResolver、ThemeResolver等等,但并不影响我们对整个SpringMVC的工作原理的理解,此处并不具体说明。
    1)初始化Context
         见下图DispatcherServlet的继承结构,其中,HttpServletBean主要功能是在初始化(init)时将servlet的配置参 数(init-param)转换成Servlet的属性,FrameworkServlet主要功能是与ApplicationContext的集成,因 此Context的初始化工作主要在FrameworkServlet中进行。

       
         Context初始化的过程可以通过如下过程来描述:HttServletBean.init --> FrameworkServlet.initServletBean --> FrameworkServlet.initWebApplicationContext。具体的初始化过程可见如下代码: 

         FrameworkServlet.initWebApplicationContext

    Java代码  收藏代码
    1. protected WebApplicationContext initWebApplicationContext() throws BeansException {  
    2.     WebApplicationContext parent = WebApplicationContextUtils.getWebApplicationContext(getServletContext());  
    3.     WebApplicationContext wac = createWebApplicationContext(parent);  
    4.   
    5.     if (!this.refreshEventReceived) {  
    6.         // Apparently not a ConfigurableApplicationContext with refresh support:  
    7.         // triggering initial onRefresh manually here.  
    8.         onRefresh(wac);  
    9.     }  
    10.   
    11.     if (this.publishContext) {  
    12.         // Publish the context as a servlet context attribute.  
    13.         String attrName = getServletContextAttributeName();  
    14.         getServletContext().setAttribute(attrName, wac);  
    15.         if (logger.isDebugEnabled()) {  
    16.             logger.debug("Published WebApplicationContext of servlet '" + getServletName() +  
    17.                     "' as ServletContext attribute with name [" + attrName + "]");  
    18.         }  
    19.     }  
    20.   
    21.     return wac;  
    22. }  

         FrameworkServlet.createWebApplicationContext

    Java代码  收藏代码
    1. protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent)  
    2.         throws BeansException {  
    3.   
    4.     if (logger.isDebugEnabled()) {  
    5.         logger.debug("Servlet with name '" + getServletName() +  
    6.                 "' will try to create custom WebApplicationContext context of class '" +  
    7.                 getContextClass().getName() + "'" + ", using parent context [" + parent + "]");  
    8.     }  
    9.     if (!ConfigurableWebApplicationContext.class.isAssignableFrom(getContextClass())) {  
    10.         throw new ApplicationContextException(  
    11.                 "Fatal initialization error in servlet with name '" + getServletName() +  
    12.                 "': custom WebApplicationContext class [" + getContextClass().getName() +  
    13.                 "] is not of type ConfigurableWebApplicationContext");  
    14.     }  
    15.   
    16.     ConfigurableWebApplicationContext wac =  
    17.             (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(getContextClass());  
    18.     wac.setParent(parent);  
    19.     wac.setServletContext(getServletContext());  
    20.     wac.setServletConfig(getServletConfig());  
    21.     wac.setNamespace(getNamespace());  
    22.     wac.setConfigLocation(getContextConfigLocation());  
    23.     wac.addApplicationListener(new SourceFilteringListener(wac, this));  
    24.   
    25.     postProcessWebApplicationContext(wac);  
    26.     wac.refresh();  
    27.   
    28.     return wac;  
    29. }  

     

    2)初始化策略
       具体与SpringMVC相关的策略在DispatcherServlet中初始化,DispatcherServlet的类定义被加载时,如下初始化代码段被执行:

    Java代码  收藏代码
    1.         static {  
    2. // Load default strategy implementations from properties file.  
    3. // This is currently strictly internal and not meant to be customized  
    4. // by application developers.  
    5. try {  
    6.     ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, DispatcherServlet.class);  
    7.     defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);  
    8. }  
    9. catch (IOException ex) {  
    10.     throw new IllegalStateException("Could not load 'DispatcherServlet.properties': " + ex.getMessage());  
    11. }  

       我们可以看到,SpringMVC的策略在与DispatcherServlet同目录的Dispatcher.properties文件中配置,如下是Spring2.5的默认配置策略

    Dispatcher.properties 写道
    # Default implementation classes for DispatcherServlet's strategy interfaces.
    # Used as fallback when no matching beans are found in the DispatcherServlet context.
    # Not meant to be customized by application developers.

    org.springframework.web.servlet.LocaleResolver=org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver

    org.springframework.web.servlet.ThemeResolver=org.springframework.web.servlet.theme.FixedThemeResolver

    org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,
    org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping

    org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,
    org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,
    org.springframework.web.servlet.mvc.throwaway.ThrowawayControllerHandlerAdapter,
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter

    org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator

    org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver

        当然,我们可以变更其处理策略,通过上面部分,我们知道,FrameworkServlet实现了ApplicationListener,并在构建 WebApplicationContext后,将自身(this)向WebApplicationContext注册,因此 WebApplicationContext初始化完毕之后,将发送ContextRefreshedEvent事件,该事件实际上被 DispatcherServlet处理,处理过程如下:

        FrameworkServlet.onApplicationEvent --> DispatcherServlet.onRefresh --> DispatcherServlet.initStrategies

        DispatcherServlet.initStrategies代码如下,具体处理过程可参见Spring源代码

    Java代码  收藏代码
    1. protected void initStrategies(ApplicationContext context) {  
    2. initMultipartResolver(context);  
    3. initLocaleResolver(context);  
    4. initThemeResolver(context);  
    5. initHandlerMappings(context);  
    6. initHandlerAdapters(context);  
    7. initHandlerExceptionResolvers(context);  
    8. initRequestToViewNameTranslator(context);  
    9. initViewResolvers(context);  

    3.请求处理流程

        SpringMVC的请求处理从doService-->doDispatch为入口,实际上,我们只要紧紧抓住HandlerMapping、 HandlerAdapter、ViewResolver这三个核心对象,SpringMVC的一整个运行机制看起来将非常简单,其主要处理流程包括:

    1)将请求映射到具体的执行处理链,见如下代码

    Java代码  收藏代码
    1.                            // Determine handler for the current request.  
    2. mappedHandler = getHandler(processedRequest, false);  
    3. if (mappedHandler == null || mappedHandler.getHandler() == null) {  
    4.     noHandlerFound(processedRequest, response);  
    5.     return;  
    6. }  

       具体看一下getHandler是如何处理的

    Java代码  收藏代码
    1. protected HandlerExecutionChain getHandler(HttpServletRequest request, boolean cache) throws Exception {  
    2. HandlerExecutionChain handler =  
    3.         (HandlerExecutionChain) request.getAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE);  
    4. if (handler != null) {  
    5.     if (!cache) {  
    6.         request.removeAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE);  
    7.     }  
    8.     return handler;  
    9. }  
    10.   
    11. Iterator it = this.handlerMappings.iterator();  
    12. while (it.hasNext()) {  
    13.     HandlerMapping hm = (HandlerMapping) it.next();  
    14.     if (logger.isDebugEnabled()) {  
    15.         logger.debug("Testing handler map [" + hm  + "] in DispatcherServlet with name '" +  
    16.                 getServletName() + "'");  
    17.     }  
    18.     handler = hm.getHandler(request);  
    19.     if (handler != null) {  
    20.         if (cache) {  
    21.             request.setAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE, handler);  
    22.         }  
    23.         return handler;  
    24.     }  
    25. }  
    26. return null;  

       可以看到,仅仅是遍历每一个HandlerMapping,如果能够其能够处理,则返回执行处理链(HandleExecuteChain)

    2)执行处理链的拦截器列表的preHandle方法,如果执行时返回false,表示该拦截器已处理完请求要求停止执行后续的工作,则倒序执行所有已执行过的拦截器的afterCompletion方法,并返回

    Java代码  收藏代码
    1. // Apply preHandle methods of registered interceptors.  
    2. HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();  
    3. if (interceptors != null) {  
    4.     for (int i = 0; i < interceptors.length; i++) {  
    5.         HandlerInterceptor interceptor = interceptors[i];  
    6.         if (!interceptor.preHandle(processedRequest, response, mappedHandler.getHandler())) {  
    7.             triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);  
    8.             return;  
    9.         }  
    10.         interceptorIndex = i;  
    11.     }  
    12. }  

     3)根据处理对象获得处理器适配器(HandlerAdapter),并由处理适配器负责最终的请求处理,并返回ModelAndView(mv),关于处理器适配器的作用,见第2部分的说明

    Java代码  收藏代码
    1. // Actually invoke the handler.  
    2. HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());  
    3. mv = ha.handle(processedRequest, response, mappedHandler.getHandler());  

       具体看getHandlerAdapter如何工作

    Java代码  收藏代码
    1. protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {  
    2.     Iterator it = this.handlerAdapters.iterator();  
    3.     while (it.hasNext()) {  
    4.         HandlerAdapter ha = (HandlerAdapter) it.next();  
    5.         if (logger.isDebugEnabled()) {  
    6.             logger.debug("Testing handler adapter [" + ha + "]");  
    7.         }  
    8.         if (ha.supports(handler)) {  
    9.             return ha;  
    10.         }  
    11.     }  
    12.     throw new ServletException("No adapter for handler [" + handler +  
    13.             "]: Does your handler implement a supported interface like Controller?");  
    14. }  

        非常简单,仅仅是依次询问HandlerAdapter列表是否支持处理当前的处理器对象

    4)倒序执行处理链拦截器列表的postHandle方法

    Java代码  收藏代码
    1. // Apply postHandle methods of registered interceptors.  
    2. if (interceptors != null) {  
    3.     for (int i = interceptors.length - 1; i >= 0; i--) {  
    4.         HandlerInterceptor interceptor = interceptors[i];  
    5.         interceptor.postHandle(processedRequest, response, mappedHandler.getHandler(), mv);  
    6.     }  
    7. }  

    5)根据ViewResolver获取相应的View实例,并生成视图响应给客户端

    Java代码  收藏代码
    1. // Did the handler return a view to render?  
    2. if (mv != null && !mv.wasCleared()) {  
    3.     render(mv, processedRequest, response);  
    4. }  
    5. else {  
    6.     if (logger.isDebugEnabled()) {  
    7.         logger.debug("Null ModelAndView returned to DispatcherServlet with name '" +  
    8.                 getServletName() + "': assuming HandlerAdapter completed request handling");  
    9.     }  
    10. }  

        再看看render方法

    Java代码  收藏代码
    1. protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response)  
    2.         throws Exception {  
    3.   
    4.     // Determine locale for request and apply it to the response.  
    5.     Locale locale = this.localeResolver.resolveLocale(request);  
    6.     response.setLocale(locale);  
    7.   
    8.     View view = null;  
    9.   
    10.     if (mv.isReference()) {  
    11.         // We need to resolve the view name.  
    12.         view = resolveViewName(mv.getViewName(), mv.getModelInternal(), locale, request);  
    13.         if (view == null) {  
    14.             throw new ServletException("Could not resolve view with name '" + mv.getViewName() +  
    15.                     "' in servlet with name '" + getServletName() + "'");  
    16.         }  
    17.     }  
    18.     else {  
    19.         // No need to lookup: the ModelAndView object contains the actual View object.  
    20.         view = mv.getView();  
    21.         if (view == null) {  
    22.             throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " +  
    23.                     "View object in servlet with name '" + getServletName() + "'");  
    24.         }  
    25.     }  
    26.   
    27.     // Delegate to the View object for rendering.  
    28.     if (logger.isDebugEnabled()) {  
    29.         logger.debug("Rendering view [" + view + "] in DispatcherServlet with name '" + getServletName() + "'");  
    30.     }  
    31.     view.render(mv.getModelInternal(), request, response);  
    32. }  

    6)倒序执行处理链拦截器列表的afterCompletion方法

    Java代码  收藏代码
      1. private void triggerAfterCompletion(  
      2.         HandlerExecutionChain mappedHandler, int interceptorIndex,  
      3.         HttpServletRequest request, HttpServletResponse response, Exception ex)  
      4.         throws Exception {  
      5.   
      6.     // Apply afterCompletion methods of registered interceptors.  
      7.     if (mappedHandler != null) {  
      8.         HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();  
      9.         if (interceptors != null) {  
      10.             for (int i = interceptorIndex; i >= 0; i--) {  
      11.                 HandlerInterceptor interceptor = interceptors[i];  
      12.                 try {  
      13.                     interceptor.afterCompletion(request, response, mappedHandler.getHandler(), ex);  
      14.                 }  
      15.                 catch (Throwable ex2) {  
      16.                     logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);  
      17.                 }  
      18.             }  
      19.         }  
      20.     }  
      21. 4.请求-处理链映射(HandlerMapping)
           HandlerMapping定义了请求与处理链之间的映射的策略,见如下接口。

        Java代码  收藏代码
        1. public interface HandlerMapping {  
        2.  String PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE = HandlerMapping.class.getName() + ".pathWithinHandlerMapping";  
        3.   
        4.  HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;  

           主要的继承类和继承结构如下

           其中
        *AbstractHandlerMapping:定义了HandlerMapping实现的最基础的部分内容,包括拦截器列表和默认处理对象
        *AbstractUrlHandlerMapping:在AbstractHandlerMapping的基础上,定义了从URL到处理对象的映射关系管理,其主要处理过程如下
           getHandlerInternal:

        Java代码  收藏代码
        1. protected Object getHandlerInternal(HttpServletRequest request) throws Exception {  
        2.     String lookupPath = this.urlPathHelper.getLookupPathForRequest(request);  
        3.     if (logger.isDebugEnabled()) {  
        4.         logger.debug("Looking up handler for [" + lookupPath + "]");  
        5.     }  
        6.     Object handler = lookupHandler(lookupPath, request);  
        7.     if (handler == null) {  
        8.         // We need to care for the default handler directly, since we need to  
        9.         // expose the PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE for it as well.  
        10.         Object rawHandler = null;  
        11.         if ("/".equals(lookupPath)) {  
        12.             rawHandler = getRootHandler();  
        13.         }  
        14.         if (rawHandler == null) {  
        15.             rawHandler = getDefaultHandler();  
        16.         }  
        17.         if (rawHandler != null) {  
        18.             validateHandler(rawHandler, request);  
        19.             handler = buildPathExposingHandler(rawHandler, lookupPath);  
        20.         }  
        21.     }  
        22.     return handler;  
        23. }  

           lookupHandler:

        Java代码  收藏代码
        1. protected Object lookupHandler(String urlPath, HttpServletRequest request) throws Exception {  
        2.     // Direct match?  
        3.     Object handler = this.handlerMap.get(urlPath);  
        4.     if (handler != null) {  
        5.         validateHandler(handler, request);  
        6.         return buildPathExposingHandler(handler, urlPath);  
        7.     }  
        8.     // Pattern match?  
        9.     String bestPathMatch = null;  
        10.     for (Iterator it = this.handlerMap.keySet().iterator(); it.hasNext();) {  
        11.         String registeredPath = (String) it.next();  
        12.         if (getPathMatcher().match(registeredPath, urlPath) &&  
        13.                 (bestPathMatch == null || bestPathMatch.length() < registeredPath.length())) {  
        14.             bestPathMatch = registeredPath;  
        15.         }  
        16.     }  
        17.     if (bestPathMatch != null) {  
        18.         handler = this.handlerMap.get(bestPathMatch);  
        19.         validateHandler(handler, request);  
        20.         String pathWithinMapping = getPathMatcher().extractPathWithinPattern(bestPathMatch, urlPath);  
        21.         return buildPathExposingHandler(handler, pathWithinMapping);  
        22.     }  
        23.     // No handler found...  
        24.     return null;  
        25. }  

         另外,其定义了Handler的注册方法registerHandler

        *AbstractDetectingUrlHandlerMapping:AbstractDetectingUrlHandlerMapping 通过继承ApplicationObjectSupport实现了ApplicationContextAware接口,在初始化完成之后自动通过 ApplicationObjectSupport.setApplicationContext-->AbstractDetectingUrlHandlerMapping.initApplicationContext-->AbstractDetectingUrlHandlerMapping.detectHandlers 调用detectHandlers函数,该函数将注册到ApplicationContext的所有Bean对象逐一检查,由其子类实现的 determineUrlsForHandler判断每个Bean对象对应的URL,并将URL与Bean的关系通过 AbstractUrlHandlerMapping.registerHandler注册

        Java代码  收藏代码
        1. protected void detectHandlers() throws BeansException {  
        2.     if (logger.isDebugEnabled()) {  
        3.         logger.debug("Looking for URL mappings in application context: " + getApplicationContext());  
        4.     }  
        5.     String[] beanNames = (this.detectHandlersInAncestorContexts ?  
        6.             BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :  
        7.             getApplicationContext().getBeanNamesForType(Object.class));  
        8.   
        9.     // Take any bean name or alias that begins with a slash.  
        10.     for (int i = 0; i < beanNames.length; i++) {  
        11.         String beanName = beanNames[i];  
        12.         String[] urls = determineUrlsForHandler(beanName);  
        13.         if (!ObjectUtils.isEmpty(urls)) {  
        14.             // URL paths found: Let's consider it a handler.  
        15.             registerHandler(urls, beanName);  
        16.         }  
        17.         else {  
        18.             if (logger.isDebugEnabled()) {  
        19.                 logger.debug("Rejected bean name '" + beanNames[i] + "': no URL paths identified");  
        20.             }  
        21.         }  
        22.     }  
        23. }  

        *BeanNameUrlHandlerMapping:非常简单,其实现determineUrlsForHandler函数,如果一个Bean以“/”开头,则认为是一个处理器类,并且以bean的名字作为映射的url,处理过程如下

        Java代码  收藏代码
        1. protected String[] determineUrlsForHandler(String beanName) {  
        2.     List urls = new ArrayList();  
        3.     if (beanName.startsWith("/")) {  
        4.         urls.add(beanName);  
        5.     }  
        6.     String[] aliases = getApplicationContext().getAliases(beanName);  
        7.     for (int j = 0; j < aliases.length; j++) {  
        8.         if (aliases[j].startsWith("/")) {  
        9.             urls.add(aliases[j]);  
        10.         }  
        11.     }  
        12.     return StringUtils.toStringArray(urls);  
        13. }  

        *DefaultAnnotationHandlerMapping:实现determineUrlsForHandler函数,检查每个Bean 对象的类或者方法有没有RequestMapping这个Annotation,如果有,则将相应配置的URL作为该Bean对应处理的URL,处理过程 如下

        Java代码  收藏代码
        1. protected String[] determineUrlsForHandler(String beanName) {  
        2.         ApplicationContext context = getApplicationContext();  
        3.         Class<?> handlerType = context.getType(beanName);  
        4.         RequestMapping mapping = AnnotationUtils.findAnnotation(handlerType, RequestMapping.class);  
        5.   
        6.         if (mapping == null && context instanceof ConfigurableApplicationContext &&  
        7.                 context.containsBeanDefinition(beanName)) {  
        8.             ConfigurableApplicationContext cac = (ConfigurableApplicationContext) context;  
        9.             BeanDefinition bd = cac.getBeanFactory().getMergedBeanDefinition(beanName);  
        10.             if (bd instanceof AbstractBeanDefinition) {  
        11.                 AbstractBeanDefinition abd = (AbstractBeanDefinition) bd;  
        12.                 if (abd.hasBeanClass()) {  
        13.                     Class<?> beanClass = abd.getBeanClass();  
        14.                     mapping = AnnotationUtils.findAnnotation(beanClass, RequestMapping.class);  
        15.                 }  
        16.             }  
        17.         }  
        18.   
        19.         if (mapping != null) {  
        20.             // @RequestMapping found at type level  
        21.             this.cachedMappings.put(handlerType, mapping);  
        22.             Set<String> urls = new LinkedHashSet<String>();  
        23.             String[] paths = mapping.value();  
        24.             if (paths.length > 0) {  
        25.                 // @RequestMapping specifies paths at type level  
        26.                 for (String path : paths) {  
        27.                     addUrlsForPath(urls, path);  
        28.                 }  
        29.                 return StringUtils.toStringArray(urls);  
        30.             }  
        31.             else {  
        32.                 // actual paths specified by @RequestMapping at method level  
        33.                 return determineUrlsForHandlerMethods(handlerType);  
        34.             }  
        35.         }  
        36.         else if (AnnotationUtils.findAnnotation(handlerType, Controller.class) != null) {  
        37.             // @RequestMapping to be introspected at method level  
        38.             return determineUrlsForHandlerMethods(handlerType);  
        39.         }  
        40.         else {  
        41.             return null;  
        42.         }  
        43.     }  

        5.处理器适配器(HandlerAdapter)
           HandlerAdapter定义了处理类如何处理请求的策略,见如下接口

        Java代码  收藏代码
        1.    public interface HandlerAdapter {  
        2.     boolean supports(Object handler);  
        3.     ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;  
        4.     long getLastModified(HttpServletRequest request, Object handler);  
        5. }  

           通过实现特定的策略,可以灵活地将任意对象转换成请求处理对象,主要实现包括:

        1)SimpleControllerHandlerAdapter/HttpRequestHandlerAdapter/SimpleServletHandlerAdapter/ThrowawayController
           非常简单,面向实现实现了特定接口的处理类的情形,仅仅做一个代理执行处理,看一下其中SimpleControllerHandlerAdapter的代码如下,其特定处理实现了Controller接口的处理类

        Java代码  收藏代码
        1. public class SimpleControllerHandlerAdapter implements HandlerAdapter {  
        2.   
        3.     public boolean supports(Object handler) {  
        4.         return (handler instanceof Controller);  
        5.     }  
        6.   
        7.     public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)  
        8.             throws Exception {  
        9.   
        10.         return ((Controller) handler).handleRequest(request, response);  
        11.     }  
        12.   
        13.     public long getLastModified(HttpServletRequest request, Object handler) {  
        14.         if (handler instanceof LastModified) {  
        15.             return ((LastModified) handler).getLastModified(request);  
        16.         }  
        17.         return -1L;  
        18.     }  
        19.   
        20. }  

        2)AnnotationMethodHandlerAdapter
           通过配置特定的Annotation,定义了该如何注入参数、调用哪个方法、对返回参数如何处理,主要过程如下(AnnotationMethodHandlerAdapter.invokeHandlerMethod)

        Java代码  收藏代码
        1. try {  
        2.             ServletHandlerMethodResolver methodResolver = getMethodResolver(handler);  
        3.             Method handlerMethod = methodResolver.resolveHandlerMethod(request);  
        4.             ServletHandlerMethodInvoker methodInvoker = new ServletHandlerMethodInvoker(methodResolver);  
        5.             ServletWebRequest webRequest = new ServletWebRequest(request, response);  
        6.             ExtendedModelMap implicitModel = new ExtendedModelMap();  
        7.   
        8.             Object result = methodInvoker.invokeHandlerMethod(handlerMethod, handler, webRequest, implicitModel);  
        9.             ModelAndView mav = methodInvoker.getModelAndView(handlerMethod, result, implicitModel, webRequest);  
        10.             methodInvoker.updateSessionAttributes(  
        11.                     handler, (mav != null ? mav.getModel() : null), implicitModel, webRequest);  
        12.             return mav;  
        13.         }  
        14.         catch (NoSuchRequestHandlingMethodException ex) {  
        15.             return handleNoSuchRequestHandlingMethod(ex, request, response);  
        16.         }  

        *ServletHandlerMethodResolver(AnnotationMethodHandlerAdapter内部类):该类通过请求URL、请求Method和处理类的RequestMapping定义,最终确定该使用处理类的哪个方法来处理请求
        *ServletHandlerMethodInvoker(AnnotationMethodHandlerAdapter内部类):检查处理类相应处 理方法的参数以及相关的Annotation配置,确定如何转换需要的参数传入调用方法,并最终调用返回ModelAndView
        6.视图策略(ViewResolver)
          ViewResolver定义了如何确定处理视图的View对象的策略,见如下接口

        Java代码  收藏代码
        1. public interface ViewResolver {  
        2.     View resolveViewName(String viewName, Locale locale) throws Exception;  

  • 相关阅读:
    CPA财务管理例题汇总
    Vulkan(1)用apispec生成Vulkan库
    Vulkan(0)搭建环境-清空窗口
    [译]可见性判断之门系统
    《资本论》核心思想
    [译]为任意网格计算tangent空间的基向量
    [译]Vulkan教程(33)多重采样
    [译]Vulkan教程(32)生成mipmap
    [译]Vulkan教程(31)加载模型
    [译]Vulkan教程(30)深度缓存
  • 原文地址:https://www.cnblogs.com/sand-tiny/p/3745186.html
Copyright © 2011-2022 走看看