主頁 > 後端開發 > Servlet和springMVC

Servlet和springMVC

2023-03-26 07:44:52 後端開發

什么是Servlet?

  1. Servlet是使用Java語言撰寫的運行在服務器端的程式,狹義的Servlet是指Java語言實作的一個介面,廣義的Servlet是指任何實作了這個Servlet介面的類,一般情況下,人們將Servlet理解為后者,Servlet 主要用于處理客戶端傳來的 HTTP 請求,并回傳一個回應,它能夠處理的請求有doGet()和doPost()等方法
  2. Servlet由Servlet容器提供,所謂的Servlet容器是指提供了Servlet 功能的服務器(本書中指Tomcat),Servlet容器將Servlet動態地加載到服務器上,與HTTP 協議相關的Servlet使用HTTP請求和HTTP回應與客戶端進行互動,因此,Servlet容器支持所有HTTP協議的請求和回應,Servlet應用程式的體系結構如圖所示,<<javaWeb程式設計教程>>

什么是SpringMVC?

  1. Spring MVC一開始就定位于一個較為松散的組合,展示給用戶的視圖(View)、控制器回傳的資料模型(Model)、定位視圖的視圖決議器(ViewResolver)和處理配接器(HandlerAdapter)等內容都是獨立的,換句話說,通過Spring MVC很容易把后臺的資料轉換為各種型別的資料,以滿足移動互聯網資料多樣化的要求,例如,Spring MVC可以十分方便地轉換為目前最常用的JSON資料集,也可以轉換為PDF、Excel和XML等,加之Spring MVC是基于Spring基礎框架派生出來的Web框架,所以它天然就可以十分方便地整合到Spring框架中,而Spring整合Struts2還是比較繁復的.
  2. mvc架構設計:處理請求先到達控制器(Controller),控制器的作用是進行請求分發,這樣它會根據請求的內容去訪問模型層(Model);在現今互聯網系統中,資料主要從資料庫和NoSQL中來,而且對于資料庫而言往往還存在事務的機制,為了適應這樣的變化,設計者會把模型層再細分為兩層,即服務層(Service)和資料訪問層(DAO);當控制器獲取到由模型層回傳的資料后,就將資料渲染到視圖中,這樣就能夠展現給用戶了
  3.  

     圖取自于<<深入淺出springboot2.x>>書籍

 

思考和疑問

早些年的時候,使用servlet開發web程式, 一般都是繼承HttpServlet介面,請求訪問時直接根據類名呼叫.但這樣寫的結果是,一個類只能處理一個請求.專案結構大概長這樣

使用SpringMVC框架后,只需要配置簡單的@RequestMapping("")就可以找到對應的方法,原來的servlet呢? 對springMVC的了解還是不夠詳細,所以

繼續探討以下幾個問題

1.SpringMVC如何代替Servlet?

 

 

 可以看到DispatcherServlet繼承自HttpServlet,  前端控制器其實就相當于一個Servlet.

 2. SpringMVC的作業流程?

 

圖取自于<<深入淺出springboot2.x>>書籍

基于springboot開發使得SpringMVC的使用更為簡便,可以通過Spring Boot的配置來定制這些組件的初始化

  1. /*
     * Copyright 2002-2019 the original author or authors.
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *      https://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    package org.springframework.web.servlet;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Locale;
    import java.util.Map;
    import java.util.Properties;
    import java.util.Set;
    import java.util.stream.Collectors;
    
    import javax.servlet.DispatcherType;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    
    import org.springframework.beans.factory.BeanFactoryUtils;
    import org.springframework.beans.factory.BeanInitializationException;
    import org.springframework.beans.factory.NoSuchBeanDefinitionException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ConfigurableApplicationContext;
    import org.springframework.context.i18n.LocaleContext;
    import org.springframework.core.annotation.AnnotationAwareOrderComparator;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.support.PropertiesLoaderUtils;
    import org.springframework.core.log.LogFormatUtils;
    import org.springframework.http.server.ServletServerHttpRequest;
    import org.springframework.lang.Nullable;
    import org.springframework.ui.context.ThemeSource;
    import org.springframework.util.ClassUtils;
    import org.springframework.util.StringUtils;
    import org.springframework.web.context.WebApplicationContext;
    import org.springframework.web.context.request.ServletWebRequest;
    import org.springframework.web.context.request.async.WebAsyncManager;
    import org.springframework.web.context.request.async.WebAsyncUtils;
    import org.springframework.web.multipart.MultipartException;
    import org.springframework.web.multipart.MultipartHttpServletRequest;
    import org.springframework.web.multipart.MultipartResolver;
    import org.springframework.web.util.NestedServletException;
    import org.springframework.web.util.WebUtils;
    
    /**
     * Central dispatcher for HTTP request handlers/controllers, e.g. for web UI controllers
     * or HTTP-based remote service exporters. Dispatches to registered handlers for processing
     * a web request, providing convenient mapping and exception handling facilities.
     *
     * <p>This servlet is very flexible: It can be used with just about any workflow, with the
     * installation of the appropriate adapter classes. It offers the following functionality
     * that distinguishes it from other request-driven web MVC frameworks:
     *
     * <ul>
     * <li>It is based around a JavaBeans configuration mechanism.
     *
     * <li>It can use any {@link HandlerMapping} implementation - pre-built or provided as part
     * of an application - to control the routing of requests to handler objects. Default is
     * {@link org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping} and
     * {@link org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping}.
     * HandlerMapping objects can be defined as beans in the servlet's application context,
     * implementing the HandlerMapping interface, overriding the default HandlerMapping if
     * present. HandlerMappings can be given any bean name (they are tested by type).
     *
     * <li>It can use any {@link HandlerAdapter}; this allows for using any handler interface.
     * Default adapters are {@link org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter},
     * {@link org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter}, for Spring's
     * {@link org.springframework.web.HttpRequestHandler} and
     * {@link org.springframework.web.servlet.mvc.Controller} interfaces, respectively. A default
     * {@link org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter}
     * will be registered as well. HandlerAdapter objects can be added as beans in the
     * application context, overriding the default HandlerAdapters. Like HandlerMappings,
     * HandlerAdapters can be given any bean name (they are tested by type).
     *
     * <li>The dispatcher's exception resolution strategy can be specified via a
     * {@link HandlerExceptionResolver}, for example mapping certain exceptions to error pages.
     * Default are
     * {@link org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver},
     * {@link org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver}, and
     * {@link org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver}.
     * These HandlerExceptionResolvers can be overridden through the application context.
     * HandlerExceptionResolver can be given any bean name (they are tested by type).
     *
     * <li>Its view resolution strategy can be specified via a {@link ViewResolver}
     * implementation, resolving symbolic view names into View objects. Default is
     * {@link org.springframework.web.servlet.view.InternalResourceViewResolver}.
     * ViewResolver objects can be added as beans in the application context, overriding the
     * default ViewResolver. ViewResolvers can be given any bean name (they are tested by type).
     *
     * <li>If a {@link View} or view name is not supplied by the user, then the configured
     * {@link RequestToViewNameTranslator} will translate the current request into a view name.
     * The corresponding bean name is "viewNameTranslator"; the default is
     * {@link org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator}.
     *
     * <li>The dispatcher's strategy for resolving multipart requests is determined by a
     * {@link org.springframework.web.multipart.MultipartResolver} implementation.
     * Implementations for Apache Commons FileUpload and Servlet 3 are included; the typical
     * choice is {@link org.springframework.web.multipart.commons.CommonsMultipartResolver}.
     * The MultipartResolver bean name is "multipartResolver"; default is none.
     *
     * <li>Its locale resolution strategy is determined by a {@link LocaleResolver}.
     * Out-of-the-box implementations work via HTTP accept header, cookie, or session.
     * The LocaleResolver bean name is "localeResolver"; default is
     * {@link org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver}.
     *
     * <li>Its theme resolution strategy is determined by a {@link ThemeResolver}.
     * Implementations for a fixed theme and for cookie and session storage are included.
     * The ThemeResolver bean name is "themeResolver"; default is
     * {@link org.springframework.web.servlet.theme.FixedThemeResolver}.
     * </ul>
     *
     * <p><b>NOTE: The {@code @RequestMapping} annotation will only be processed if a
     * corresponding {@code HandlerMapping} (for type-level annotations) and/or
     * {@code HandlerAdapter} (for method-level annotations) is present in the dispatcher.</b>
     * This is the case by default. However, if you are defining custom {@code HandlerMappings}
     * or {@code HandlerAdapters}, then you need to make sure that a corresponding custom
     * {@code RequestMappingHandlerMapping} and/or {@code RequestMappingHandlerAdapter}
     * is defined as well - provided that you intend to use {@code @RequestMapping}.
     *
     * <p><b>A web application can define any number of DispatcherServlets.</b>
     * Each servlet will operate in its own namespace, loading its own application context
     * with mappings, handlers, etc. Only the root application context as loaded by
     * {@link org.springframework.web.context.ContextLoaderListener}, if any, will be shared.
     *
     * <p>As of Spring 3.1, {@code DispatcherServlet} may now be injected with a web
     * application context, rather than creating its own internally. This is useful in Servlet
     * 3.0+ environments, which support programmatic registration of servlet instances.
     * See the {@link #DispatcherServlet(WebApplicationContext)} javadoc for details.
     *
     * @author Rod Johnson
     * @author Juergen Hoeller
     * @author Rob Harrop
     * @author Chris Beams
     * @author Rossen Stoyanchev
     * @see org.springframework.web.HttpRequestHandler
     * @see org.springframework.web.servlet.mvc.Controller
     * @see org.springframework.web.context.ContextLoaderListener
     */
    @SuppressWarnings("serial")
    public class DispatcherServlet extends FrameworkServlet {
    
        /** Well-known name for the MultipartResolver object in the bean factory for this namespace. */
        public static final String MULTIPART_RESOLVER_BEAN_NAME = "multipartResolver";
    
        /** Well-known name for the LocaleResolver object in the bean factory for this namespace. */
        public static final String LOCALE_RESOLVER_BEAN_NAME = "localeResolver";
    
        /** Well-known name for the ThemeResolver object in the bean factory for this namespace. */
        public static final String THEME_RESOLVER_BEAN_NAME = "themeResolver";
    
        /**
         * Well-known name for the HandlerMapping object in the bean factory for this namespace.
         * Only used when "detectAllHandlerMappings" is turned off.
         * @see #setDetectAllHandlerMappings
         */
        public static final String HANDLER_MAPPING_BEAN_NAME = "handlerMapping";
    
        /**
         * Well-known name for the HandlerAdapter object in the bean factory for this namespace.
         * Only used when "detectAllHandlerAdapters" is turned off.
         * @see #setDetectAllHandlerAdapters
         */
        public static final String HANDLER_ADAPTER_BEAN_NAME = "handlerAdapter";
    
        /**
         * Well-known name for the HandlerExceptionResolver object in the bean factory for this namespace.
         * Only used when "detectAllHandlerExceptionResolvers" is turned off.
         * @see #setDetectAllHandlerExceptionResolvers
         */
        public static final String HANDLER_EXCEPTION_RESOLVER_BEAN_NAME = "handlerExceptionResolver";
    
        /**
         * Well-known name for the RequestToViewNameTranslator object in the bean factory for this namespace.
         */
        public static final String REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME = "viewNameTranslator";
    
        /**
         * Well-known name for the ViewResolver object in the bean factory for this namespace.
         * Only used when "detectAllViewResolvers" is turned off.
         * @see #setDetectAllViewResolvers
         */
        public static final String VIEW_RESOLVER_BEAN_NAME = "viewResolver";
    
        /**
         * Well-known name for the FlashMapManager object in the bean factory for this namespace.
         */
        public static final String FLASH_MAP_MANAGER_BEAN_NAME = "flashMapManager";
    
        /**
         * Request attribute to hold the current web application context.
         * Otherwise only the global web app context is obtainable by tags etc.
         * @see org.springframework.web.servlet.support.RequestContextUtils#findWebApplicationContext
         */
        public static final String WEB_APPLICATION_CONTEXT_ATTRIBUTE = DispatcherServlet.class.getName() + ".CONTEXT";
    
        /**
         * Request attribute to hold the current LocaleResolver, retrievable by views.
         * @see org.springframework.web.servlet.support.RequestContextUtils#getLocaleResolver
         */
        public static final String LOCALE_RESOLVER_ATTRIBUTE = DispatcherServlet.class.getName() + ".LOCALE_RESOLVER";
    
        /**
         * Request attribute to hold the current ThemeResolver, retrievable by views.
         * @see org.springframework.web.servlet.support.RequestContextUtils#getThemeResolver
         */
        public static final String THEME_RESOLVER_ATTRIBUTE = DispatcherServlet.class.getName() + ".THEME_RESOLVER";
    
        /**
         * Request attribute to hold the current ThemeSource, retrievable by views.
         * @see org.springframework.web.servlet.support.RequestContextUtils#getThemeSource
         */
        public static final String THEME_SOURCE_ATTRIBUTE = DispatcherServlet.class.getName() + ".THEME_SOURCE";
    
        /**
         * Name of request attribute that holds a read-only {@code Map<String,?>}
         * with "input" flash attributes saved by a previous request, if any.
         * @see org.springframework.web.servlet.support.RequestContextUtils#getInputFlashMap(HttpServletRequest)
         */
        public static final String INPUT_FLASH_MAP_ATTRIBUTE = DispatcherServlet.class.getName() + ".INPUT_FLASH_MAP";
    
        /**
         * Name of request attribute that holds the "output" {@link FlashMap} with
         * attributes to save for a subsequent request.
         * @see org.springframework.web.servlet.support.RequestContextUtils#getOutputFlashMap(HttpServletRequest)
         */
        public static final String OUTPUT_FLASH_MAP_ATTRIBUTE = DispatcherServlet.class.getName() + ".OUTPUT_FLASH_MAP";
    
        /**
         * Name of request attribute that holds the {@link FlashMapManager}.
         * @see org.springframework.web.servlet.support.RequestContextUtils#getFlashMapManager(HttpServletRequest)
         */
        public static final String FLASH_MAP_MANAGER_ATTRIBUTE = DispatcherServlet.class.getName() + ".FLASH_MAP_MANAGER";
    
        /**
         * Name of request attribute that exposes an Exception resolved with a
         * {@link HandlerExceptionResolver} but where no view was rendered
         * (e.g. setting the status code).
         */
        public static final String EXCEPTION_ATTRIBUTE = DispatcherServlet.class.getName() + ".EXCEPTION";
    
        /** Log category to use when no mapped handler is found for a request. */
        public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.servlet.PageNotFound";
    
        /**
         * Name of the class path resource (relative to the DispatcherServlet class)
         * that defines DispatcherServlet's default strategy names.
         */
        private static final String DEFAULT_STRATEGIES_PATH = "DispatcherServlet.properties";
    
        /**
         * Common prefix that DispatcherServlet's default strategy attributes start with.
         */
        private static final String DEFAULT_STRATEGIES_PREFIX = "org.springframework.web.servlet";
    
        /** Additional logger to use when no mapped handler is found for a request. */
        protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY);
    
        private static final Properties defaultStrategies;
    
        static {
            // Load default strategy implementations from properties file.
            // This is currently strictly internal and not meant to be customized
            // by application developers.
            try {
                ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, DispatcherServlet.class);
                defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
            }
            catch (IOException ex) {
                throw new IllegalStateException("Could not load '" + DEFAULT_STRATEGIES_PATH + "': " + ex.getMessage());
            }
        }
    
        /** Detect all HandlerMappings or just expect "handlerMapping" bean?. */
        private boolean detectAllHandlerMappings = true;
    
        /** Detect all HandlerAdapters or just expect "handlerAdapter" bean?. */
        private boolean detectAllHandlerAdapters = true;
    
        /** Detect all HandlerExceptionResolvers or just expect "handlerExceptionResolver" bean?. */
        private boolean detectAllHandlerExceptionResolvers = true;
    
        /** Detect all ViewResolvers or just expect "viewResolver" bean?. */
        private boolean detectAllViewResolvers = true;
    
        /** Throw a NoHandlerFoundException if no Handler was found to process this request? *.*/
        private boolean throwExceptionIfNoHandlerFound = false;
    
        /** Perform cleanup of request attributes after include request?. */
        private boolean cleanupAfterInclude = true;
    
        /** MultipartResolver used by this servlet. */
        @Nullable
        private MultipartResolver multipartResolver;
    
        /** LocaleResolver used by this servlet. */
        @Nullable
        private LocaleResolver localeResolver;
    
        /** ThemeResolver used by this servlet. */
        @Nullable
        private ThemeResolver themeResolver;
    
        /** List of HandlerMappings used by this servlet. */
        @Nullable
        private List<HandlerMapping> handlerMappings;
    
        /** List of HandlerAdapters used by this servlet. */
        @Nullable
        private List<HandlerAdapter> handlerAdapters;
    
        /** List of HandlerExceptionResolvers used by this servlet. */
        @Nullable
        private List<HandlerExceptionResolver> handlerExceptionResolvers;
    
        /** RequestToViewNameTranslator used by this servlet. */
        @Nullable
        private RequestToViewNameTranslator viewNameTranslator;
    
        /** FlashMapManager used by this servlet. */
        @Nullable
        private FlashMapManager flashMapManager;
    
        /** List of ViewResolvers used by this servlet. */
        @Nullable
        private List<ViewResolver> viewResolvers;
    
    
        /**
         * Create a new {@code DispatcherServlet} that will create its own internal web
         * application context based on defaults and values provided through servlet
         * init-params. Typically used in Servlet 2.5 or earlier environments, where the only
         * option for servlet registration is through {@code web.xml} which requires the use
         * of a no-arg constructor.
         * <p>Calling {@link #setContextConfigLocation} (init-param 'contextConfigLocation')
         * will dictate which XML files will be loaded by the
         * {@linkplain #DEFAULT_CONTEXT_CLASS default XmlWebApplicationContext}
         * <p>Calling {@link #setContextClass} (init-param 'contextClass') overrides the
         * default {@code XmlWebApplicationContext} and allows for specifying an alternative class,
         * such as {@code AnnotationConfigWebApplicationContext}.
         * <p>Calling {@link #setContextInitializerClasses} (init-param 'contextInitializerClasses')
         * indicates which {@code ApplicationContextInitializer} classes should be used to
         * further configure the internal application context prior to refresh().
         * @see #DispatcherServlet(WebApplicationContext)
         */
        public DispatcherServlet() {
            super();
            setDispatchOptionsRequest(true);
        }
    
        /**
         * Create a new {@code DispatcherServlet} with the given web application context. This
         * constructor is useful in Servlet 3.0+ environments where instance-based registration
         * of servlets is possible through the {@link ServletContext#addServlet} API.
         * <p>Using this constructor indicates that the following properties / init-params
         * will be ignored:
         * <ul>
         * <li>{@link #setContextClass(Class)} / 'contextClass'</li>
         * <li>{@link #setContextConfigLocation(String)} / 'contextConfigLocation'</li>
         * <li>{@link #setContextAttribute(String)} / 'contextAttribute'</li>
         * <li>{@link #setNamespace(String)} / 'namespace'</li>
         * </ul>
         * <p>The given web application context may or may not yet be {@linkplain
         * ConfigurableApplicationContext#refresh() refreshed}. If it has <strong>not</strong>
         * already been refreshed (the recommended approach), then the following will occur:
         * <ul>
         * <li>If the given context does not already have a {@linkplain
         * ConfigurableApplicationContext#setParent parent}, the root application context
         * will be set as the parent.</li>
         * <li>If the given context has not already been assigned an {@linkplain
         * ConfigurableApplicationContext#setId id}, one will be assigned to it</li>
         * <li>{@code ServletContext} and {@code ServletConfig} objects will be delegated to
         * the application context</li>
         * <li>{@link #postProcessWebApplicationContext} will be called</li>
         * <li>Any {@code ApplicationContextInitializer}s specified through the
         * "contextInitializerClasses" init-param or through the {@link
         * #setContextInitializers} property will be applied.</li>
         * <li>{@link ConfigurableApplicationContext#refresh refresh()} will be called if the
         * context implements {@link ConfigurableApplicationContext}</li>
         * </ul>
         * If the context has already been refreshed, none of the above will occur, under the
         * assumption that the user has performed these actions (or not) per their specific
         * needs.
         * <p>See {@link org.springframework.web.WebApplicationInitializer} for usage examples.
         * @param webApplicationContext the context to use
         * @see #initWebApplicationContext
         * @see #configureAndRefreshWebApplicationContext
         * @see org.springframework.web.WebApplicationInitializer
         */
        public DispatcherServlet(WebApplicationContext webApplicationContext) {
            super(webApplicationContext);
            setDispatchOptionsRequest(true);
        }
    
    
        /**
         * Set whether to detect all HandlerMapping beans in this servlet's context. Otherwise,
         * just a single bean with name "handlerMapping" will be expected.
         * <p>Default is "true". Turn this off if you want this servlet to use a single
         * HandlerMapping, despite multiple HandlerMapping beans being defined in the context.
         */
        public void setDetectAllHandlerMappings(boolean detectAllHandlerMappings) {
            this.detectAllHandlerMappings = detectAllHandlerMappings;
        }
    
        /**
         * Set whether to detect all HandlerAdapter beans in this servlet's context. Otherwise,
         * just a single bean with name "handlerAdapter" will be expected.
         * <p>Default is "true". Turn this off if you want this servlet to use a single
         * HandlerAdapter, despite multiple HandlerAdapter beans being defined in the context.
         */
        public void setDetectAllHandlerAdapters(boolean detectAllHandlerAdapters) {
            this.detectAllHandlerAdapters = detectAllHandlerAdapters;
        }
    
        /**
         * Set whether to detect all HandlerExceptionResolver beans in this servlet's context. Otherwise,
         * just a single bean with name "handlerExceptionResolver" will be expected.
         * <p>Default is "true". Turn this off if you want this servlet to use a single
         * HandlerExceptionResolver, despite multiple HandlerExceptionResolver beans being defined in the context.
         */
        public void setDetectAllHandlerExceptionResolvers(boolean detectAllHandlerExceptionResolvers) {
            this.detectAllHandlerExceptionResolvers = detectAllHandlerExceptionResolvers;
        }
    
        /**
         * Set whether to detect all ViewResolver beans in this servlet's context. Otherwise,
         * just a single bean with name "viewResolver" will be expected.
         * <p>Default is "true". Turn this off if you want this servlet to use a single
         * ViewResolver, despite multiple ViewResolver beans being defined in the context.
         */
        public void setDetectAllViewResolvers(boolean detectAllViewResolvers) {
            this.detectAllViewResolvers = detectAllViewResolvers;
        }
    
        /**
         * Set whether to throw a NoHandlerFoundException when no Handler was found for this request.
         * This exception can then be caught with a HandlerExceptionResolver or an
         * {@code @ExceptionHandler} controller method.
         * <p>Note that if {@link org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler}
         * is used, then requests will always be forwarded to the default servlet and a
         * NoHandlerFoundException would never be thrown in that case.
         * <p>Default is "false", meaning the DispatcherServlet sends a NOT_FOUND error through the
         * Servlet response.
         * @since 4.0
         */
        public void setThrowExceptionIfNoHandlerFound(boolean throwExceptionIfNoHandlerFound) {
            this.throwExceptionIfNoHandlerFound = throwExceptionIfNoHandlerFound;
        }
    
        /**
         * Set whether to perform cleanup of request attributes after an include request, that is,
         * whether to reset the original state of all request attributes after the DispatcherServlet
         * has processed within an include request. Otherwise, just the DispatcherServlet's own
         * request attributes will be reset, but not model attributes for JSPs or special attributes
         * set by views (for example, JSTL's).
         * <p>Default is "true", which is strongly recommended. Views should not rely on request attributes
         * having been set by (dynamic) includes. This allows JSP views rendered by an included controller
         * to use any model attributes, even with the same names as in the main JSP, without causing side
         * effects. Only turn this off for special needs, for example to deliberately allow main JSPs to
         * access attributes from JSP views rendered by an included controller.
         */
        public void setCleanupAfterInclude(boolean cleanupAfterInclude) {
            this.cleanupAfterInclude = cleanupAfterInclude;
        }
    
    
        /**
         * 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);
        }
    
        /**
         * Initialize the MultipartResolver used by this class.
         * <p>If no bean is defined with the given name in the BeanFactory for this namespace,
         * no multipart handling is provided.
         */
        private void initMultipartResolver(ApplicationContext context) {
            try {
                this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class);
                if (logger.isTraceEnabled()) {
                    logger.trace("Detected " + this.multipartResolver);
                }
                else if (logger.isDebugEnabled()) {
                    logger.debug("Detected " + this.multipartResolver.getClass().getSimpleName());
                }
            }
            catch (NoSuchBeanDefinitionException ex) {
                // Default is no multipart resolver.
                this.multipartResolver = null;
                if (logger.isTraceEnabled()) {
                    logger.trace("No MultipartResolver '" + MULTIPART_RESOLVER_BEAN_NAME + "' declared");
                }
            }
        }
    
        /**
         * Initialize the LocaleResolver used by this class.
         * <p>If no bean is defined with the given name in the BeanFactory for this namespace,
         * we default to AcceptHeaderLocaleResolver.
         */
        private void initLocaleResolver(ApplicationContext context) {
            try {
                this.localeResolver = context.getBean(LOCALE_RESOLVER_BEAN_NAME, LocaleResolver.class);
                if (logger.isTraceEnabled()) {
                    logger.trace("Detected " + this.localeResolver);
                }
                else if (logger.isDebugEnabled()) {
                    logger.debug("Detected " + this.localeResolver.getClass().getSimpleName());
                }
            }
            catch (NoSuchBeanDefinitionException ex) {
                // We need to use the default.
                this.localeResolver = getDefaultStrategy(context, LocaleResolver.class);
                if (logger.isTraceEnabled()) {
                    logger.trace("No LocaleResolver '" + LOCALE_RESOLVER_BEAN_NAME +
                            "': using default [" + this.localeResolver.getClass().getSimpleName() + "]");
                }
            }
        }
    
        /**
         * Initialize the ThemeResolver used by this class.
         * <p>If no bean is defined with the given name in the BeanFactory for this namespace,
         * we default to a FixedThemeResolver.
         */
        private void initThemeResolver(ApplicationContext context) {
            try {
                this.themeResolver = context.getBean(THEME_RESOLVER_BEAN_NAME, ThemeResolver.class);
                if (logger.isTraceEnabled()) {
                    logger.trace("Detected " + this.themeResolver);
                }
                else if (logger.isDebugEnabled()) {
                    logger.debug("Detected " + this.themeResolver.getClass().getSimpleName());
                }
            }
            catch (NoSuchBeanDefinitionException ex) {
                // We need to use the default.
                this.themeResolver = getDefaultStrategy(context, ThemeResolver.class);
                if (logger.isTraceEnabled()) {
                    logger.trace("No ThemeResolver '" + THEME_RESOLVER_BEAN_NAME +
                            "': using default [" + this.themeResolver.getClass().getSimpleName() + "]");
                }
            }
        }
    
        /**
         * Initialize the HandlerMappings used by this class.
         * <p>If no HandlerMapping beans are defined in the BeanFactory for this namespace,
         * we default to BeanNameUrlHandlerMapping.
         */
        private void initHandlerMappings(ApplicationContext context) {
            this.handlerMappings = null;
    
            if (this.detectAllHandlerMappings) {
                // Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
                Map<String, HandlerMapping> matchingBeans =
                        BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
                if (!matchingBeans.isEmpty()) {
                    this.handlerMappings = new ArrayList<>(matchingBeans.values());
                    // We keep HandlerMappings in sorted order.
                    AnnotationAwareOrderComparator.sort(this.handlerMappings);
                }
            }
            else {
                try {
                    HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
                    this.handlerMappings = Collections.singletonList(hm);
                }
                catch (NoSuchBeanDefinitionException ex) {
                    // Ignore, we'll add a default HandlerMapping later.
                }
            }
    
            // Ensure we have at least one HandlerMapping, by registering
            // a default HandlerMapping if no other mappings are found.
            if (this.handlerMappings == null) {
                this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
                if (logger.isTraceEnabled()) {
                    logger.trace("No HandlerMappings declared for servlet '" + getServletName() +
                            "': using default strategies from DispatcherServlet.properties");
                }
            }
        }
    
        /**
         * Initialize the HandlerAdapters used by this class.
         * <p>If no HandlerAdapter beans are defined in the BeanFactory for this namespace,
         * we default to SimpleControllerHandlerAdapter.
         */
        private void initHandlerAdapters(ApplicationContext context) {
            this.handlerAdapters = null;
    
            if (this.detectAllHandlerAdapters) {
                // Find all HandlerAdapters in the ApplicationContext, including ancestor contexts.
                Map<String, HandlerAdapter> matchingBeans =
                        BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerAdapter.class, true, false);
                if (!matchingBeans.isEmpty()) {
                    this.handlerAdapters = new ArrayList<>(matchingBeans.values());
                    // We keep HandlerAdapters in sorted order.
                    AnnotationAwareOrderComparator.sort(this.handlerAdapters);
                }
            }
            else {
                try {
                    HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class);
                    this.handlerAdapters = Collections.singletonList(ha);
                }
                catch (NoSuchBeanDefinitionException ex) {
                    // Ignore, we'll add a default HandlerAdapter later.
                }
            }
    
            // Ensure we have at least some HandlerAdapters, by registering
            // default HandlerAdapters if no other adapters are found.
            if (this.handlerAdapters == null) {
                this.handlerAdapters = getDefaultStrategies(context, HandlerAdapter.class);
                if (logger.isTraceEnabled()) {
                    logger.trace("No HandlerAdapters declared for servlet '" + getServletName() +
                            "': using default strategies from DispatcherServlet.properties");
                }
            }
        }
    
        /**
         * Initialize the HandlerExceptionResolver used by this class.
         * <p>If no bean is defined with the given name in the BeanFactory for this namespace,
         * we default to no exception resolver.
         */
        private void initHandlerExceptionResolvers(ApplicationContext context) {
            this.handlerExceptionResolvers = null;
    
            if (this.detectAllHandlerExceptionResolvers) {
                // Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts.
                Map<String, HandlerExceptionResolver> matchingBeans = BeanFactoryUtils
                        .beansOfTypeIncludingAncestors(context, HandlerExceptionResolver.class, true, false);
                if (!matchingBeans.isEmpty()) {
                    this.handlerExceptionResolvers = new ArrayList<>(matchingBeans.values());
                    // We keep HandlerExceptionResolvers in sorted order.
                    AnnotationAwareOrderComparator.sort(this.handlerExceptionResolvers);
                }
            }
            else {
                try {
                    HandlerExceptionResolver her =
                            context.getBean(HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class);
                    this.handlerExceptionResolvers = Collections.singletonList(her);
                }
                catch (NoSuchBeanDefinitionException ex) {
                    // Ignore, no HandlerExceptionResolver is fine too.
                }
            }
    
            // Ensure we have at least some HandlerExceptionResolvers, by registering
            // default HandlerExceptionResolvers if no other resolvers are found.
            if (this.handlerExceptionResolvers == null) {
                this.handlerExceptionResolvers = getDefaultStrategies(context, HandlerExceptionResolver.class);
                if (logger.isTraceEnabled()) {
                    logger.trace("No HandlerExceptionResolvers declared in servlet '" + getServletName() +
                            "': using default strategies from DispatcherServlet.properties");
                }
            }
        }
    
        /**
         * Initialize the RequestToViewNameTranslator used by this servlet instance.
         * <p>If no implementation is configured then we default to DefaultRequestToViewNameTranslator.
         */
        private void initRequestToViewNameTranslator(ApplicationContext context) {
            try {
                this.viewNameTranslator =
                        context.getBean(REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME, RequestToViewNameTranslator.class);
                if (logger.isTraceEnabled()) {
                    logger.trace("Detected " + this.viewNameTranslator.getClass().getSimpleName());
                }
                else if (logger.isDebugEnabled()) {
                    logger.debug("Detected " + this.viewNameTranslator);
                }
            }
            catch (NoSuchBeanDefinitionException ex) {
                // We need to use the default.
                this.viewNameTranslator = getDefaultStrategy(context, RequestToViewNameTranslator.class);
                if (logger.isTraceEnabled()) {
                    logger.trace("No RequestToViewNameTranslator '" + REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME +
                            "': using default [" + this.viewNameTranslator.getClass().getSimpleName() + "]");
                }
            }
        }
    
        /**
         * Initialize the ViewResolvers used by this class.
         * <p>If no ViewResolver beans are defined in the BeanFactory for this
         * namespace, we default to InternalResourceViewResolver.
         */
        private void initViewResolvers(ApplicationContext context) {
            this.viewResolvers = null;
    
            if (this.detectAllViewResolvers) {
                // Find all ViewResolvers in the ApplicationContext, including ancestor contexts.
                Map<String, ViewResolver> matchingBeans =
                        BeanFactoryUtils.beansOfTypeIncludingAncestors(context, ViewResolver.class, true, false);
                if (!matchingBeans.isEmpty()) {
                    this.viewResolvers = new ArrayList<>(matchingBeans.values());
                    // We keep ViewResolvers in sorted order.
                    AnnotationAwareOrderComparator.sort(this.viewResolvers);
                }
            }
            else {
                try {
                    ViewResolver vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class);
                    this.viewResolvers = Collections.singletonList(vr);
                }
                catch (NoSuchBeanDefinitionException ex) {
                    // Ignore, we'll add a default ViewResolver later.
                }
            }
    
            // Ensure we have at least one ViewResolver, by registering
            // a default ViewResolver if no other resolvers are found.
            if (this.viewResolvers == null) {
                this.viewResolvers = getDefaultStrategies(context, ViewResolver.class);
                if (logger.isTraceEnabled()) {
                    logger.trace("No ViewResolvers declared for servlet '" + getServletName() +
                            "': using default strategies from DispatcherServlet.properties");
                }
            }
        }
    
        /**
         * Initialize the {@link FlashMapManager} used by this servlet instance.
         * <p>If no implementation is configured then we default to
         * {@code org.springframework.web.servlet.support.DefaultFlashMapManager}.
         */
        private void initFlashMapManager(ApplicationContext context) {
            try {
                this.flashMapManager = context.getBean(FLASH_MAP_MANAGER_BEAN_NAME, FlashMapManager.class);
                if (logger.isTraceEnabled()) {
                    logger.trace("Detected " + this.flashMapManager.getClass().getSimpleName());
                }
                else if (logger.isDebugEnabled()) {
                    logger.debug("Detected " + this.flashMapManager);
                }
            }
            catch (NoSuchBeanDefinitionException ex) {
                // We need to use the default.
                this.flashMapManager = getDefaultStrategy(context, FlashMapManager.class);
                if (logger.isTraceEnabled()) {
                    logger.trace("No FlashMapManager '" + FLASH_MAP_MANAGER_BEAN_NAME +
                            "': using default [" + this.flashMapManager.getClass().getSimpleName() + "]");
                }
            }
        }
    
        /**
         * Return this servlet's ThemeSource, if any; else return {@code null}.
         * <p>Default is to return the WebApplicationContext as ThemeSource,
         * provided that it implements the ThemeSource interface.
         * @return the ThemeSource, if any
         * @see #getWebApplicationContext()
         */
        @Nullable
        public final ThemeSource getThemeSource() {
            return (getWebApplicationContext() instanceof ThemeSource ? (ThemeSource) getWebApplicationContext() : null);
        }
    
        /**
         * Obtain this servlet's MultipartResolver, if any.
         * @return the MultipartResolver used by this servlet, or {@code null} if none
         * (indicating that no multipart support is available)
         */
        @Nullable
        public final MultipartResolver getMultipartResolver() {
            return this.multipartResolver;
        }
    
        /**
         * Return the configured {@link HandlerMapping} beans that were detected by
         * type in the {@link WebApplicationContext} or initialized based on the
         * default set of strategies from {@literal DispatcherServlet.properties}.
         * <p><strong>Note:</strong> This method may return {@code null} if invoked
         * prior to {@link #onRefresh(ApplicationContext)}.
         * @return an immutable list with the configured mappings, or {@code null}
         * if not initialized yet
         * @since 5.0
         */
        @Nullable
        public final List<HandlerMapping> getHandlerMappings() {
            return (this.handlerMappings != null ? Collections.unmodifiableList(this.handlerMappings) : null);
        }
    
        /**
         * Return the default strategy object for the given strategy interface.
         * <p>The default implementation delegates to {@link #getDefaultStrategies},
         * expecting a single object in the list.
         * @param context the current WebApplicationContext
         * @param strategyInterface the strategy interface
         * @return the corresponding strategy object
         * @see #getDefaultStrategies
         */
        protected <T> T getDefaultStrategy(ApplicationContext context, Class<T> strategyInterface) {
            List<T> strategies = getDefaultStrategies(context, strategyInterface);
            if (strategies.size() != 1) {
                throw new BeanInitializationException(
                        "DispatcherServlet needs exactly 1 strategy for interface [" + strategyInterface.getName() + "]");
            }
            return strategies.get(0);
        }
    
        /**
         * Create a List of default strategy objects for the given strategy interface.
         * <p>The default implementation uses the "DispatcherServlet.properties" file (in the same
         * package as the DispatcherServlet class) to determine the class names. It instantiates
         * the strategy objects through the context's BeanFactory.
         * @param context the current WebApplicationContext
         * @param strategyInterface the strategy interface
         * @return the List of corresponding strategy objects
         */
        @SuppressWarnings("unchecked")
        protected <T> List<T> getDefaultStrategies(ApplicationContext context, Class<T> strategyInterface) {
            String key = strategyInterface.getName();
            String value = defaultStrategies.getProperty(key);
            if (value != null) {
                String[] classNames = StringUtils.commaDelimitedListToStringArray(value);
                List<T> strategies = new ArrayList<>(classNames.length);
                for (String className : classNames) {
                    try {
                        Class<?> clazz = ClassUtils.forName(className, DispatcherServlet.class.getClassLoader());
                        Object strategy = createDefaultStrategy(context, clazz);
                        strategies.add((T) strategy);
                    }
                    catch (ClassNotFoundException ex) {
                        throw new BeanInitializationException(
                                "Could not find DispatcherServlet's default strategy class [" + className +
                                "] for interface [" + key + "]", ex);
                    }
                    catch (LinkageError err) {
                        throw new BeanInitializationException(
                                "Unresolvable class definition for DispatcherServlet's default strategy class [" +
                                className + "] for interface [" + key + "]", err);
                    }
                }
                return strategies;
            }
            else {
                return new LinkedList<>();
            }
        }
    
        /**
         * Create a default strategy.
         * <p>The default implementation uses
         * {@link org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean}.
         * @param context the current WebApplicationContext
         * @param clazz the strategy implementation class to instantiate
         * @return the fully configured strategy instance
         * @see org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory()
         * @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean
         */
        protected Object createDefaultStrategy(ApplicationContext context, Class<?> clazz) {
            return context.getAutowireCapableBeanFactory().createBean(clazz);
        }
    
    
        /**
         * Exposes the DispatcherServlet-specific request attributes and delegates to {@link #doDispatch}
         * for the actual dispatching.
         */
        @Override
        protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
            logRequest(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<>();
                Enumeration<?> attrNames = request.getAttributeNames();
                while (attrNames.hasMoreElements()) {
                    String attrName = (String) attrNames.nextElement();
                    if (this.cleanupAfterInclude || attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) {
                        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());
    
            if (this.flashMapManager != null) {
                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()) {
                    // Restore the original attribute snapshot, in case of an include.
                    if (attributesSnapshot != null) {
                        restoreAttributesAfterInclude(request, attributesSnapshot);
                    }
                }
            }
        }
    
        private void logRequest(HttpServletRequest request) {
            LogFormatUtils.traceDebug(logger, traceOn -> {
                String params;
                if (isEnableLoggingRequestDetails()) {
                    params = request.getParameterMap().entrySet().stream()
                            .map(entry -> entry.getKey() + ":" + Arrays.toString(entry.getValue()))
                            .collect(Collectors.joining(", "));
                }
                else {
                    params = (request.getParameterMap().isEmpty() ? "" : "masked");
                }
    
                String queryString = request.getQueryString();
                String queryClause = (StringUtils.hasLength(queryString) ? "?" + queryString : "");
                String dispatchType = (!request.getDispatcherType().equals(DispatcherType.REQUEST) ?
                        "\"" + request.getDispatcherType().name() + "\" dispatch for " : "");
                String message = (dispatchType + request.getMethod() + " \"" + getRequestUri(request) +
                        queryClause + "\", parameters={" + params + "}");
    
                if (traceOn) {
                    List<String> values = Collections.list(request.getHeaderNames());
                    String headers = values.size() > 0 ? "masked" : "";
                    if (isEnableLoggingRequestDetails()) {
                        headers = values.stream().map(name -> name + ":" + Collections.list(request.getHeaders(name)))
                                .collect(Collectors.joining(", "));
                    }
                    return message + ", headers={" + headers + "} in DispatcherServlet '" + getServletName() + "'";
                }
                else {
                    return message;
                }
            });
        }
    
        /**
         * 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) {
                        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 (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
                            return;
                        }
                    }
    
                    if (!mappedHandler.applyPreHandle(processedRequest, response)) {
                        return;
                    }
    
                    // Actually invoke the handler.
                    mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
    
                    if (asyncManager.isConcurrentHandlingStarted()) {
                        return;
                    }
    
                    applyDefaultViewName(processedRequest, mv);
                    mappedHandler.applyPostHandle(processedRequest, response, mv);
                }
                catch (Exception ex) {
                    dispatchException = ex;
                }
                catch (Throwable err) {
                    // As of 4.3, we're processing Errors thrown from handler methods as well,
                    // making them available for @ExceptionHandler methods and other scenarios.
                    dispatchException = new NestedServletException("Handler dispatch failed", err);
                }
                processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
            }
            catch (Exception ex) {
                triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
            }
            catch (Throwable err) {
                triggerAfterCompletion(processedRequest, response, mappedHandler,
                        new NestedServletException("Handler processing failed", err));
            }
            finally {
                if (asyncManager.isConcurrentHandlingStarted()) {
                    // Instead of postHandle and afterCompletion
                    if (mappedHandler != null) {
                        mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
                    }
                }
                else {
                    // Clean up any resources used by a multipart request.
                    if (multipartRequestParsed) {
                        cleanupMultipart(processedRequest);
                    }
                }
            }
        }
    
        /**
         * Do we need view name translation?
         */
        private void applyDefaultViewName(HttpServletRequest request, @Nullable ModelAndView mv) throws Exception {
            if (mv != null && !mv.hasView()) {
                String defaultViewName = getDefaultViewName(request);
                if (defaultViewName != null) {
                    mv.setViewName(defaultViewName);
                }
            }
        }
    
        /**
         * Handle the result of handler selection and handler invocation, which is
         * either a ModelAndView or an Exception to be resolved to a ModelAndView.
         */
        private void processDispatchResult(HttpServletRequest request, HttpServletResponse response,
                @Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv,
                @Nullable Exception exception) throws Exception {
    
            boolean errorView = false;
    
            if (exception != null) {
                if (exception instanceof ModelAndViewDefiningException) {
                    logger.debug("ModelAndViewDefiningException encountered", exception);
                    mv = ((ModelAndViewDefiningException) exception).getModelAndView();
                }
                else {
                    Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
                    mv = processHandlerException(request, response, handler, exception);
                    errorView = (mv != null);
                }
            }
    
            // Did the handler return a view to render?
            if (mv != null && !mv.wasCleared()) {
                render(mv, request, response);
                if (errorView) {
                    WebUtils.clearErrorRequestAttributes(request);
                }
            }
            else {
                if (logger.isTraceEnabled()) {
                    logger.trace("No view rendering, null ModelAndView returned.");
                }
            }
    
            if (WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
                // Concurrent handling started during a forward
                return;
            }
    
            if (mappedHandler != null) {
                // Exception (if any) is already handled..
                mappedHandler.triggerAfterCompletion(request, response, null);
            }
        }
    
        /**
         * Build a LocaleContext for the given request, exposing the request's primary locale as current locale.
         * <p>The default implementation uses the dispatcher's LocaleResolver to obtain the current locale,
         * which might change during a request.
         * @param request current HTTP request
         * @return the corresponding LocaleContext
         */
        @Override
        protected LocaleContext buildLocaleContext(final HttpServletRequest request) {
            LocaleResolver lr = this.localeResolver;
            if (lr instanceof LocaleContextResolver) {
                return ((LocaleContextResolver) lr).resolveLocaleContext(request);
            }
            else {
                return () -> (lr != null ? lr.resolveLocale(request) : request.getLocale());
            }
        }
    
        /**
         * Convert the request into a multipart request, and make multipart resolver available.
         * <p>If no multipart resolver is set, simply use the existing request.
         * @param request current HTTP request
         * @return the processed request (multipart wrapper if necessary)
         * @see MultipartResolver#resolveMultipart
         */
        protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException {
            if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) {
                if (WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class) != null) {
                    if (request.getDispatcherType().equals(DispatcherType.REQUEST)) {
                        logger.trace("Request already resolved to MultipartHttpServletRequest, e.g. by MultipartFilter");
                    }
                }
                else if (hasMultipartException(request)) {
                    logger.debug("Multipart resolution previously failed for current request - " +
                            "skipping re-resolution for undisturbed error rendering");
                }
                else {
                    try {
                        return this.multipartResolver.resolveMultipart(request);
                    }
                    catch (MultipartException ex) {
                        if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) != null) {
                            logger.debug("Multipart resolution failed for error dispatch", ex);
                            // Keep processing error dispatch with regular request handle below
                        }
                        else {
                            throw ex;
                        }
                    }
                }
            }
            // If not returned before: return original request.
            return request;
        }
    
        /**
         * Check "javax.servlet.error.exception" attribute for a multipart exception.
         */
        private boolean hasMultipartException(HttpServletRequest request) {
            Throwable error = (Throwable) request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE);
            while (error != null) {
                if (error instanceof MultipartException) {
                    return true;
                }
                error = error.getCause();
            }
            return false;
        }
    
        /**
         * Clean up any resources used by the given multipart request (if any).
         * @param request current HTTP request
         * @see MultipartResolver#cleanupMultipart
         */
        protected void cleanupMultipart(HttpServletRequest request) {
            if (this.multipartResolver != null) {
                MultipartHttpServletRequest multipartRequest =
                        WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
                if (multipartRequest != null) {
                    this.multipartResolver.cleanupMultipart(multipartRequest);
                }
            }
        }
    
        /**
         * Return the HandlerExecutionChain for this request.
         * <p>Tries all handler mappings in order.
         * @param request current HTTP request
         * @return the HandlerExecutionChain, or {@code null} if no handler could be found
         */
        @Nullable
        protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
            if (this.handlerMappings != null) {
                for (HandlerMapping mapping : this.handlerMappings) {
                    HandlerExecutionChain handler = mapping.getHandler(request);
                    if (handler != null) {
                        return handler;
                    }
                }
            }
            return null;
        }
    
        /**
         * No handler found -> set appropriate HTTP response status.
         * @param request current HTTP request
         * @param response current HTTP response
         * @throws Exception if preparing the response failed
         */
        protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception {
            if (pageNotFoundLogger.isWarnEnabled()) {
                pageNotFoundLogger.warn("No mapping for " + request.getMethod() + " " + getRequestUri(request));
            }
            if (this.throwExceptionIfNoHandlerFound) {
                throw new NoHandlerFoundException(request.getMethod(), getRequestUri(request),
                        new ServletServerHttpRequest(request).getHeaders());
            }
            else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        }
    
        /**
         * Return the HandlerAdapter for this handler object.
         * @param handler the handler object to find an adapter for
         * @throws ServletException if no HandlerAdapter can be found for the handler. This is a fatal error.
         */
        protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
            if (this.handlerAdapters != null) {
                for (HandlerAdapter adapter : this.handlerAdapters) {
                    if (adapter.supports(handler)) {
                        return adapter;
                    }
                }
            }
            throw new ServletException("No adapter for handler [" + handler +
                    "]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
        }
    
        /**
         * Determine an error ModelAndView via the registered HandlerExceptionResolvers.
         * @param request current HTTP request
         * @param response current HTTP response
         * @param handler the executed handler, or {@code null} if none chosen at the time of the exception
         * (for example, if multipart resolution failed)
         * @param ex the exception that got thrown during handler execution
         * @return a corresponding ModelAndView to forward to
         * @throws Exception if no error ModelAndView found
         */
        @Nullable
        protected ModelAndView processHandlerException(HttpServletRequest request, HttpServletResponse response,
                @Nullable Object handler, Exception ex) throws Exception {
    
            // Success and error responses may use different content types
            request.removeAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
    
            // Check registered HandlerExceptionResolvers...
            ModelAndView exMv = null;
            if (this.handlerExceptionResolvers != null) {
                for (HandlerExceptionResolver resolver : this.handlerExceptionResolvers) {
                    exMv = resolver.resolveException(request, response, handler, ex);
                    if (exMv != null) {
                        break;
                    }
                }
            }
            if (exMv != null) {
                if (exMv.isEmpty()) {
                    request.setAttribute(EXCEPTION_ATTRIBUTE, ex);
                    return null;
                }
                // We might still need view name translation for a plain error model...
                if (!exMv.hasView()) {
                    String defaultViewName = getDefaultViewName(request);
                    if (defaultViewName != null) {
                        exMv.setViewName(defaultViewName);
                    }
                }
                if (logger.isTraceEnabled()) {
                    logger.trace("Using resolved error view: " + exMv, ex);
                }
                else if (logger.isDebugEnabled()) {
                    logger.debug("Using resolved error view: " + exMv);
                }
                WebUtils.exposeErrorRequestAttributes(request, ex, getServletName());
                return exMv;
            }
    
            throw ex;
        }
    
        /**
         * Render the given ModelAndView.
         * <p>This is the last stage in handling a request. It may involve resolving the view by name.
         * @param mv the ModelAndView to render
         * @param request current HTTP servlet request
         * @param response current HTTP servlet response
         * @throws ServletException if view is missing or cannot be resolved
         * @throws Exception if there's a problem rendering the view
         */
        protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {
            // Determine locale for request and apply it to the response.
            Locale locale =
                    (this.localeResolver != null ? this.localeResolver.resolveLocale(request) : request.getLocale());
            response.setLocale(locale);
    
            View view;
            String viewName = mv.getViewName();
            if (viewName != null) {
                // We need to resolve the view name.
                view = resolveViewName(viewName, mv.getModelInternal(), locale, request);
                if (view == null) {
                    throw new ServletException("Could not resolve view with name '" + mv.getViewName() +
                            "' in servlet with name '" + getServletName() + "'");
                }
            }
            else {
                // No need to lookup: the ModelAndView object contains the actual View object.
                view = mv.getView();
                if (view == null) {
                    throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " +
                            "View object in servlet with name '" + getServletName() + "'");
                }
            }
    
            // Delegate to the View object for rendering.
            if (logger.isTraceEnabled()) {
                logger.trace("Rendering view [" + view + "] ");
            }
            try {
                if (mv.getStatus() != null) {
                    response.setStatus(mv.getStatus().value());
                }
                view.render(mv.getModelInternal(), request, response);
            }
            catch (Exception ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Error rendering view [" + view + "]", ex);
                }
                throw ex;
            }
        }
    
        /**
         * Translate the supplied request into a default view name.
         * @param request current HTTP servlet request
         * @return the view name (or {@code null} if no default found)
         * @throws Exception if view name translation failed
         */
        @Nullable
        protected String getDefaultViewName(HttpServletRequest request) throws Exception {
            return (this.viewNameTranslator != null ? this.viewNameTranslator.getViewName(request) : null);
        }
    
        /**
         * Resolve the given view name into a View object (to be rendered).
         * <p>The default implementations asks all ViewResolvers of this dispatcher.
         * Can be overridden for custom resolution strategies, potentially based on
         * specific model attributes or request parameters.
         * @param viewName the name of the view to resolve
         * @param model the model to be passed to the view
         * @param locale the current locale
         * @param request current HTTP servlet request
         * @return the View object, or {@code null} if none found
         * @throws Exception if the view cannot be resolved
         * (typically in case of problems creating an actual View object)
         * @see ViewResolver#resolveViewName
         */
        @Nullable
        protected View resolveViewName(String viewName, @Nullable Map<String, Object> model,
                Locale locale, HttpServletRequest request) throws Exception {
    
            if (this.viewResolvers != null) {
                for (ViewResolver viewResolver : this.viewResolvers) {
                    View view = viewResolver.resolveViewName(viewName, locale);
                    if (view != null) {
                        return view;
                    }
                }
            }
            return null;
        }
    
        private void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response,
                @Nullable HandlerExecutionChain mappedHandler, Exception ex) throws Exception {
    
            if (mappedHandler != null) {
                mappedHandler.triggerAfterCompletion(request, response, ex);
            }
            throw ex;
        }
    
        /**
         * Restore the request attributes after an include.
         * @param request current HTTP request
         * @param attributesSnapshot the snapshot of the request attributes before the include
         */
        @SuppressWarnings("unchecked")
        private void restoreAttributesAfterInclude(HttpServletRequest request, Map<?, ?> attributesSnapshot) {
            // Need to copy into separate Collection here, to avoid side effects
            // on the Enumeration when removing attributes.
            Set<String> attrsToCheck = new HashSet<>();
            Enumeration<?> attrNames = request.getAttributeNames();
            while (attrNames.hasMoreElements()) {
                String attrName = (String) attrNames.nextElement();
                if (this.cleanupAfterInclude || attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) {
                    attrsToCheck.add(attrName);
                }
            }
    
            // Add attributes that may have been removed
            attrsToCheck.addAll((Set<String>) attributesSnapshot.keySet());
    
            // Iterate over the attributes to check, restoring the original value
            // or removing the attribute, respectively, if appropriate.
            for (String attrName : attrsToCheck) {
                Object attrValue = attributesSnapshot.get(attrName);
                if (attrValue =https://www.cnblogs.com/july7/archive/2023/03/25/= null) {
                    request.removeAttribute(attrName);
                }
                else if (attrValue != request.getAttribute(attrName)) {
                    request.setAttribute(attrName, attrValue);
                }
            }
        }
    
        private static String getRequestUri(HttpServletRequest request) {
            String uri = (String) request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE);
            if (uri == null) {
                uri = request.getRequestURI();
            }
            return uri;
        }
    
    }
    DispatcherServlet @Controller表明這是一個控制器,然后@RequestMapping代表請求路徑和控制器(或其方法)的映射關系,它會在Web服務器啟動Spring MVC時,就被掃描到HandlerMapping的機制中存盤,之后在用戶發起請求被DispatcherServlet攔截后,通過URI和其他的條件,通過HandlerMapper機制就能找到對應的控制器(或其方法)進行回應,只是通過HandlerMapping回傳的是一個HandlerExecutionChain物件
  2. /*
     * Copyright 2002-2020 the original author or authors.
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *      https://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    package org.springframework.web.servlet;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    
    import org.springframework.lang.Nullable;
    import org.springframework.util.CollectionUtils;
    import org.springframework.util.ObjectUtils;
    
    /**
     * Handler execution chain, consisting of handler object and any handler interceptors.
     * Returned by HandlerMapping's {@link HandlerMapping#getHandler} method.
     *
     * @author Juergen Hoeller
     * @since 20.06.2003
     * @see HandlerInterceptor
     */
    public class HandlerExecutionChain {
    
        private static final Log logger = LogFactory.getLog(HandlerExecutionChain.class);
    
        private final Object handler;
    
        @Nullable
        private HandlerInterceptor[] interceptors;
    
        @Nullable
        private List<HandlerInterceptor> interceptorList;
    
        private int interceptorIndex = -1;
    
    
        /**
         * Create a new HandlerExecutionChain.
         * @param handler the handler object to execute
         */
        public HandlerExecutionChain(Object handler) {
            this(handler, (HandlerInterceptor[]) null);
        }
    
        /**
         * Create a new HandlerExecutionChain.
         * @param handler the handler object to execute
         * @param interceptors the array of interceptors to apply
         * (in the given order) before the handler itself executes
         */
        public HandlerExecutionChain(Object handler, @Nullable HandlerInterceptor... interceptors) {
            if (handler instanceof HandlerExecutionChain) {
                HandlerExecutionChain originalChain = (HandlerExecutionChain) handler;
                this.handler = originalChain.getHandler();
                this.interceptorList = new ArrayList<>();
                CollectionUtils.mergeArrayIntoCollection(originalChain.getInterceptors(), this.interceptorList);
                CollectionUtils.mergeArrayIntoCollection(interceptors, this.interceptorList);
            }
            else {
                this.handler = handler;
                this.interceptors = interceptors;
            }
        }
    
    
        /**
         * Return the handler object to execute.
         */
        public Object getHandler() {
            return this.handler;
        }
    
        /**
         * Add the given interceptor to the end of this chain.
         */
        public void addInterceptor(HandlerInterceptor interceptor) {
            initInterceptorList().add(interceptor);
        }
    
        /**
         * Add the given interceptor at the specified index of this chain.
         * @since 5.2
         */
        public void addInterceptor(int index, HandlerInterceptor interceptor) {
            initInterceptorList().add(index, interceptor);
        }
    
        /**
         * Add the given interceptors to the end of this chain.
         */
        public void addInterceptors(HandlerInterceptor... interceptors) {
            if (!ObjectUtils.isEmpty(interceptors)) {
                CollectionUtils.mergeArrayIntoCollection(interceptors, initInterceptorList());
            }
        }
    
        private List<HandlerInterceptor> initInterceptorList() {
            if (this.interceptorList == null) {
                this.interceptorList = new ArrayList<>();
                if (this.interceptors != null) {
                    // An interceptor array specified through the constructor
                    CollectionUtils.mergeArrayIntoCollection(this.interceptors, this.interceptorList);
                }
            }
            this.interceptors = null;
            return this.interceptorList;
        }
    
        /**
         * Return the array of interceptors to apply (in the given order).
         * @return the array of HandlerInterceptors instances (may be {@code null})
         */
        @Nullable
        public HandlerInterceptor[] getInterceptors() {
            if (this.interceptors == null && this.interceptorList != null) {
                this.interceptors = this.interceptorList.toArray(new HandlerInterceptor[0]);
            }
            return this.interceptors;
        }
    
    
        /**
         * Apply preHandle methods of registered interceptors.
         * @return {@code true} if the execution chain should proceed with the
         * next interceptor or the handler itself. Else, DispatcherServlet assumes
         * that this interceptor has already dealt with the response itself.
         */
        boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
            HandlerInterceptor[] interceptors = getInterceptors();
            if (!ObjectUtils.isEmpty(interceptors)) {
                for (int i = 0; i < interceptors.length; i++) {
                    HandlerInterceptor interceptor = interceptors[i];
                    if (!interceptor.preHandle(request, response, this.handler)) {
                        triggerAfterCompletion(request, response, null);
                        return false;
                    }
                    this.interceptorIndex = i;
                }
            }
            return true;
        }
    
        /**
         * Apply postHandle methods of registered interceptors.
         */
        void applyPostHandle(HttpServletRequest request, HttpServletResponse response, @Nullable ModelAndView mv)
                throws Exception {
    
            HandlerInterceptor[] interceptors = getInterceptors();
            if (!ObjectUtils.isEmpty(interceptors)) {
                for (int i = interceptors.length - 1; i >= 0; i--) {
                    HandlerInterceptor interceptor = interceptors[i];
                    interceptor.postHandle(request, response, this.handler, mv);
                }
            }
        }
    
        /**
         * Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
         * Will just invoke afterCompletion for all interceptors whose preHandle invocation
         * has successfully completed and returned true.
         */
        void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, @Nullable Exception ex)
                throws Exception {
    
            HandlerInterceptor[] interceptors = getInterceptors();
            if (!ObjectUtils.isEmpty(interceptors)) {
                for (int i = this.interceptorIndex; i >= 0; i--) {
                    HandlerInterceptor interceptor = interceptors[i];
                    try {
                        interceptor.afterCompletion(request, response, this.handler, ex);
                    }
                    catch (Throwable ex2) {
                        logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
                    }
                }
            }
        }
    
        /**
         * Apply afterConcurrentHandlerStarted callback on mapped AsyncHandlerInterceptors.
         */
        void applyAfterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response) {
            HandlerInterceptor[] interceptors = getInterceptors();
            if (!ObjectUtils.isEmpty(interceptors)) {
                for (int i = interceptors.length - 1; i >= 0; i--) {
                    HandlerInterceptor interceptor = interceptors[i];
                    if (interceptor instanceof AsyncHandlerInterceptor) {
                        try {
                            AsyncHandlerInterceptor asyncInterceptor = (AsyncHandlerInterceptor) interceptor;
                            asyncInterceptor.afterConcurrentHandlingStarted(request, response, this.handler);
                        }
                        catch (Throwable ex) {
                            if (logger.isErrorEnabled()) {
                                logger.error("Interceptor [" + interceptor + "] failed in afterConcurrentHandlingStarted", ex);
                            }
                        }
                    }
                }
            }
        }
    
    
        /**
         * Delegates to the handler's {@code toString()} implementation.
         */
        @Override
        public String toString() {
            Object handler = getHandler();
            StringBuilder sb = new StringBuilder();
            sb.append("HandlerExecutionChain with [").append(handler).append("] and ");
            if (this.interceptorList != null) {
                sb.append(this.interceptorList.size());
            }
            else if (this.interceptors != null) {
                sb.append(this.interceptors.length);
            }
            else {
                sb.append(0);
            }
            return sb.append(" interceptors").toString();
        }
    
    }
    View Code HandlerExecutionChain物件包含一個處理器(handler),這里的處理器是對控制器(controller)的包裝,因為我們的控制器方法可能存在引數,那么處理器就可以讀入HTTP和背景關系的相關引數,然后再傳遞給控制器方法,而在控制器執行完成回傳后,處理器又可以通過配置資訊對控制器的回傳結果進行處理,從這段描述中可以看出,處理器包含了控制器方法的邏輯,此外還有處理器的攔截器(interceptor),這樣就能夠通過攔截處理器進一步地增強處理器的功能,得到了處理器(handler),還需要去運行,但是我們有普通HTTP請求,也有按BeanName的請求,甚至是WebSocket的請求,所以它還需要一個配接器去運行HandlerExecutionChain物件包含的處理器,這就是HandlerAdapter介面定義的實作類,可以看到在Spring MVC中最常用的HandlerAdapter的實作類,這便是HttpRequestHandlerAdapter,通過請求的型別,DispatcherServlet就會找到它來執行Web請求的HandlerExecutionChain物件包含的內容,這樣就能夠執行我們的處理器(handler)了,只是HandlerAdapter運行HandlerExecutionChain物件這步還比較復雜,我們這里暫時不進行深入討論,放到后面再談,在處理器呼叫控制器時,它首先通過模型層得到資料,再放入資料模型中,最后將回傳模型和視圖(ModelAndView)物件,這里控制器設定的視圖名稱設定為“user/details”,這樣就走到了視圖決議器(ViewResolver),去決議視圖邏輯名稱了,在代碼清單中可以看到視圖決議器(ViewResolver)的自動初始化,為了定制InternalResourceViewResolver初始化,可以在組態檔application.properties中進行配置
  3. 在Spring Boot的機制下定制InternalResourceViewResolver這個視圖決議器的初始化,也就是在回傳視圖名稱之后,它會以前綴(prefix)和后綴(suffix)以及視圖名稱組成全路徑定位視圖,例如,在控制器中回傳的是“user/details”,那么它就會找到/WEB-INF/jsp/user/details.jsp作為視圖(View),嚴格地說,這一步也不是必需的,因為有些視圖并不需要邏輯名稱,在不需要的時候,就不再需要視圖決議器作業了
  4. 視圖決議器定位到視圖后,視圖的作用是將資料模型(Model)渲染,這樣就能夠回應用戶的請求,這一步就是視圖將資料模型渲染(View)出來,用來展示給用戶查看,按照我們控制器的回傳,就是/WEB-INF/jsp/user/details.jsp作為我們的視圖

 

個人網址 http://threenut.cn/

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/548154.html

標籤:其他

上一篇:三天吃透Spring面試八股文

下一篇:如何評價Java

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more