springboot web - 建立路由

来源:https://www.cnblogs.com/elvinle/archive/2020/02/21/12335076.html
-Advertisement-
Play Games

一. 測試代碼 @RestController @RequestMapping("/book") public class BookController { @PostMapping("add") public JsonResponse<Integer> add(@Valid @RequestBod ...


一. 測試代碼

@RestController
@RequestMapping("/book")
public class BookController {

    @PostMapping("add")
    public JsonResponse<Integer> add(@Valid @RequestBody Book book, BindingResult errors){
        //1. 對 item  數據進行驗證
        StringBuffer sb = new StringBuffer();
        if (errors.hasErrors()) {
            for (ObjectError objectError : errors.getAllErrors()) {
                sb.append(objectError.getDefaultMessage());
            }
        }
        if (sb.length() > 0) {
            return JsonResponse.error(sb.toString());
        }
        int id = BookDB.add(book);
        return JsonResponse.success(id);
    }

    @GetMapping("getById")
    public JsonResponse<Book> getById(@RequestParam("id") Integer id){
        Book book = BookDB.getById(id);
        return JsonResponse.success(book);
    }

    @GetMapping("getAll")
    public JsonResponse<List<Book>> getAll(){
        List<Book> list = BookDB.getAll();
        return JsonResponse.success(list);
    }
}

在 BookController 中, 有三個方法可以訪問.

/book/add -> add()

/book/getById -> getById()

/book/getAll -> getAll()

url 和 對應的名字, 是可以不一樣的, 比如 我新寫個方法:

@GetMapping("byWhat")
public JsonResponse<Book> getBy(){return JsonResponse.success(null);
}

此時的對應關係就是: /book/byWhat -> getBy() 方法.

這種映射, 就是一種路由關係. 通過地址路由到方法上. 

 

二. 建立路由

1. 配置文件配置

DispatcherServlet.properties 文件中配置了兩個路由處理類:

org.springframework.web.servlet.HandlerMapping=org.`.web.servlet.handler.BeanNameUrlHandlerMapping,\
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping

 

2. 配置類配置

spring-boot-autoconfigure 中, 有一塊專門對 web 進行配置的類, WebMvcAutoConfiguration 是其中之一

@Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
    SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
    mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
    mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",
            faviconRequestHandler()));
    return mapping;
}

@Bean
public ResourceHttpRequestHandler faviconRequestHandler() {
    ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
    requestHandler.setLocations(resolveFaviconLocations());
    return requestHandler;
}

 

3. 類圖

 

4. SimpleUrlHandlerMapping

由於 其 祖先類  ApplicationObjectSupport 實現了 ApplicationContextAware 介面, 所以在實例化後, 會調用  setApplicationContext() 方法:

@Override
public final void setApplicationContext(@Nullable ApplicationContext context) throws BeansException {
    if (context == null && !isContextRequired()) {
        // Reset internal context state.
        this.applicationContext = null;
        this.messageSourceAccessor = null;
    }
    else if (this.applicationContext == null) {
        // Initialize with passed-in context.
        if (!requiredContextClass().isInstance(context)) {
            throw new ApplicationContextException(
                    "Invalid application context: needs to be of type [" + requiredContextClass().getName() + "]");
        }
        this.applicationContext = context;
        this.messageSourceAccessor = new MessageSourceAccessor(context);
        initApplicationContext(context);
    }
    else {
        // Ignore reinitialization if same context passed in.
        if (this.applicationContext != context) {
            throw new ApplicationContextException(
                    "Cannot reinitialize with different application context: current one is [" +
                    this.applicationContext + "], passed-in one is [" + context + "]");
        }
    }
}

protected void initApplicationContext(ApplicationContext context) throws BeansException {
    initApplicationContext();
}

//空方法, 被子類重寫
protected void initApplicationContext() throws BeansException {
}

SimpleUrlHandlerMapping 重寫了  initApplicationContext 方法:

@Override
public void initApplicationContext() throws BeansException {
  //此處調用了 AbstractHandlerMapping 中的方法
super.initApplicationContext(); registerHandlers(this.urlMap); } protected void registerHandlers(Map<String, Object> urlMap) throws BeansException { if (urlMap.isEmpty()) { logger.warn("Neither 'urlMap' nor 'mappings' set on SimpleUrlHandlerMapping"); } else { urlMap.forEach((url, handler) -> { // Prepend with slash if not already present. if (!url.startsWith("/")) { url = "/" + url; } // Remove whitespace from handler bean name. if (handler instanceof String) { handler = ((String) handler).trim(); } registerHandler(url, handler); }); } }

在 faviconHandlerMapping() 中, 設置了 urlMap, 經過上面的方法後, 其關係為

/**/favicon.ico -> ResourceHttpRequestHandler

然後對其進行註冊:

protected void registerHandler(String urlPath, Object handler) throws BeansException, IllegalStateException {
    Assert.notNull(urlPath, "URL path must not be null");
    Assert.notNull(handler, "Handler object must not be null");
    Object resolvedHandler = handler;

    // Eagerly resolve handler if referencing singleton via name.
    if (!this.lazyInitHandlers && handler instanceof String) {
        String handlerName = (String) handler;
        ApplicationContext applicationContext = obtainApplicationContext();
        if (applicationContext.isSingleton(handlerName)) {
            resolvedHandler = applicationContext.getBean(handlerName);
        }
    }

    Object mappedHandler = this.handlerMap.get(urlPath);
    if (mappedHandler != null) {
        if (mappedHandler != resolvedHandler) {
            throw new IllegalStateException(
                    "Cannot map " + getHandlerDescription(handler) + " to URL path [" + urlPath +
                    "]: There is already " + getHandlerDescription(mappedHandler) + " mapped.");
        }
    }
    else {
        if (urlPath.equals("/")) {
            if (logger.isInfoEnabled()) {
                logger.info("Root mapping to " + getHandlerDescription(handler));
            }
            setRootHandler(resolvedHandler);
        }
        else if (urlPath.equals("/*")) {
            if (logger.isInfoEnabled()) {
                logger.info("Default mapping to " + getHandlerDescription(handler));
            }
            setDefaultHandler(resolvedHandler);
        }
        else {
            this.handlerMap.put(urlPath, resolvedHandler);
            if (logger.isInfoEnabled()) {
                logger.info("Mapped URL path [" + urlPath + "] onto " + getHandlerDescription(handler));
            }
        }
    }
}

 

5. BeanNameUrlHandlerMapping

這個類並沒有重寫   initApplicationContext() 方法. 但是他的父類 AbstractDetectingUrlHandlerMapping 重寫了此方法:

@Override
public void initApplicationContext() throws ApplicationContextException {
    super.initApplicationContext();
    detectHandlers();
}

protected void detectHandlers() throws BeansException {
    ApplicationContext applicationContext = obtainApplicationContext();
    if (logger.isDebugEnabled()) {
        logger.debug("Looking for URL mappings in application context: " + applicationContext);
    }
   //拿取容器中所有的 bean String[] beanNames
= (this.detectHandlersInAncestorContexts ? BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext, Object.class) : applicationContext.getBeanNamesForType(Object.class));
//遍歷容器中所有的 bean, 按照規則, 進行 urls 的生成工作
// Take any bean name that we can determine URLs for. for (String beanName : beanNames) {
     //這個是一個抽象方法, 留給子類BeanNameUrlHandlerMapping實現的 String[] urls
= determineUrlsForHandler(beanName); if (!ObjectUtils.isEmpty(urls)) { // URL paths found: Let's consider it a handler. registerHandler(urls, beanName); } else { if (logger.isDebugEnabled()) { logger.debug("Rejected bean name '" + beanName + "': no URL paths identified"); } } } }

接著看一下  BeanNameUrlHandlerMapping 里的方法:

public class BeanNameUrlHandlerMapping extends AbstractDetectingUrlHandlerMapping {

    /**
     * Checks name and aliases of the given bean for URLs, starting with "/".
     */
    @Override
    protected String[] determineUrlsForHandler(String beanName) {
        List<String> urls = new ArrayList<>();
        if (beanName.startsWith("/")) {
            urls.add(beanName);
        }
        String[] aliases = obtainApplicationContext().getAliases(beanName);
        for (String alias : aliases) {
            if (alias.startsWith("/")) {
                urls.add(alias);
            }
        }
        return StringUtils.toStringArray(urls);
    }
}
determineUrlsForHandler 實現了父類留的坑, 此處主要是檢測 beanName 或其別名 是否是以 "/" 開頭的, 如果是, 則對其執行註冊方法 registerHandler(與前面4里是同一個方法). 
在此例中, 並沒有 beanName 是以 "/" 開頭的, 所以這裡並沒有進行任何註冊操作.

 

6. RequestMappingHandlerMapping

RequestMappingHandlerMapping 並不是通過 initApplicationContext() 來進行掃描觸發的.

其祖先類 AbstractHandlerMethodMapping 實現了 InitializingBean 介面, 也就是說, 在屬性設置後, 會調用其 afterPropertiesSet() 方法.

但是 RequestMappingHandlerMapping 重寫了 afterPropertiesSet() 方法:

@Override
public void afterPropertiesSet() { this.config = new RequestMappingInfo.BuilderConfiguration(); this.config.setUrlPathHelper(getUrlPathHelper()); this.config.setPathMatcher(getPathMatcher()); this.config.setSuffixPatternMatch(this.useSuffixPatternMatch); this.config.setTrailingSlashMatch(this.useTrailingSlashMatch); this.config.setRegisteredSuffixPatternMatch(this.useRegisteredSuffixPatternMatch); this.config.setContentNegotiationManager(getContentNegotiationManager()); super.afterPropertiesSet(); }

super.afterPropertiesSet() 調用的就是 AbstractHandlerMethodMapping 的方法了.
@Override
public void afterPropertiesSet() {
    initHandlerMethods();
}

private static final String SCOPED_TARGET_NAME_PREFIX = "scopedTarget.";

protected void initHandlerMethods() {
    if (logger.isDebugEnabled()) {
        logger.debug("Looking for request mappings in application context: " + getApplicationContext());
    }
//獲取容器中所有的 beanName String[] beanNames
= (this.detectHandlerMethodsInAncestorContexts ? BeanFactoryUtils.beanNamesForTypeIncludingAncestors(obtainApplicationContext(), Object.class) : obtainApplicationContext().getBeanNamesForType(Object.class));
  //遍歷 beanName
for (String beanName : beanNames) {
      //判斷 beanName是否以 scopedTarget. 開頭
if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) { Class<?> beanType = null; try { beanType = obtainApplicationContext().getType(beanName); } catch (Throwable ex) { // An unresolvable bean type, probably from a lazy bean - let's ignore it. if (logger.isDebugEnabled()) { logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex); } } if (beanType != null && isHandler(beanType)) {
          //進一步處理 detectHandlerMethods(beanName); } } } handlerMethodsInitialized(getHandlerMethods()); }

isHandler() 是一個過濾方法, 判斷 bean 是否有 Controller 或 RequestMapping 註解:

@Override
protected boolean isHandler(Class<?> beanType) {
    return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
            AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
}

 

detectHandlerMethods() 能進來的, 此例中就 bookController 了.
protected void detectHandlerMethods(final Object handler) {
    Class<?> handlerType = (handler instanceof String ?
            obtainApplicationContext().getType((String) handler) : handler.getClass());

    if (handlerType != null) {
        final Class<?> userType = ClassUtils.getUserClass(handlerType);
        Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
                (MethodIntrospector.MetadataLookup<T>) method -> {
                    try {
                        return getMappingForMethod(method, userType);
                    }
                    catch (Throwable ex) {
                        throw new IllegalStateException("Invalid mapping on handler class [" +
                                userType.getName() + "]: " + method, ex);
                    }
                });
        if (logger.isDebugEnabled()) {
            logger.debug(methods.size() + " request handler methods found on " + userType + ": " + methods);
        }
        methods.forEach((method, mapping) -> {
            Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
            registerHandlerMethod(handler, invocableMethod, mapping);
        });
    }
}

methods 就是 BookController 裡面的那三個方法: add , getById, getAll

查找的基本思路:

1. 拿到spring容器中所有的 beanNames

2. 遍歷beanNames, 進行過濾, 過濾依據: bean上是否有  Controller 或  RequestMapping 註解修飾

3. 對 bean 進行處理, 拿到他和他所有父類中的方法

4. 對這些方法進行過濾, 過濾依據為: 方法上是否有  RequestMapping 註解修飾, 並創建 RequestMappingInfo 對象 - A.

5. 為 bean 也創建 RequestMappingInfo 對象 - B. 

  如果 B 為空(bean上沒有 RequestMappingInfo註解修飾), 則跳過合併操作

  如果B不為空, 則對 A 和 B 進行合併操作. 路徑 "/book/add"也就組合出來了.

protected void registerHandlerMethod(Object handler, Method method, T mapping) {
    this.mappingRegistry.register(mapping, handler, method);
}
    
public void register(T mapping, Object handler, Method method) {
    this.readWriteLock.writeLock().lock();
    try {
        HandlerMethod handlerMethod = createHandlerMethod(handler, method);
        assertUniqueMethodMapping(handlerMethod, mapping);

        if (logger.isInfoEnabled()) {
            logger.info("Mapped \"" + mapping + "\" onto " + handlerMethod);
        }
        this.mappingLookup.put(mapping, handlerMethod);

        List<String> directUrls = getDirectUrls(mapping);
        for (String url : directUrls) {
            this.urlLookup.add(url, mapping);
        }

        String name = null;
        if (getNamingStrategy() != null) {
            name = getNamingStrategy().getName(handlerMethod, mapping);
            addMappingName(name, handlerMethod);
        }

        CorsConfiguration corsConfig = initCorsConfiguration(handler, method, mapping);
        if (corsConfig != null) {
        //如果配置了跨域, 此處還會對跨域進行記錄
this.corsLookup.put(handlerMethod, corsConfig); } this.registry.put(mapping, new MappingRegistration<>(mapping, handlerMethod, directUrls, name)); } finally { this.readWriteLock.writeLock().unlock(); } }

這裡的 mappingLookup 存放的是 RequestMappingInfo -> HandlerMethod

而 urlLookup 存放的是 url -> RequestMappingInfo

private final Map<T, HandlerMethod> mappingLookup = new LinkedHashMap<>();

private final MultiValueMap<String, T> urlLookup = new LinkedMultiValueMap<>();

 





您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、JS加密之“鹽”​ 1.salt屬性“鹽":多用於密碼學,比如我們的銀行卡是六位密碼,但是實際上在銀行的系統里,我們輸入密碼後,會給原始的密碼添加若幹字元,形成更加難以破解的密碼。這個過程我們稱為”加鹽“。 """ 處理JS加密 """ import time,random ​ def getS ...
  • 逗號 用於生成一個長度為1的元組 因此需要將長度為1的元組中元素提取出來可以用 簡化賦值操作 最後 列印變數加 實現連續列印不換行的操作在python3中行不通了 ...
  • 一、DFT之前言部分 由於matlab已提供了內部函數來計算DFT、IDFT,我們只需要會調用fft、ifft函數就行; 二、函數說明: fft(x):計算N點的DFT。N是序列x的長度,即N=length(x); fft(x,L):計算L點的DFT。若LN,則將原序列x補0至L點,然後通過計算其L ...
  • 一、 功能: 尋找非零元素的索引和值 二、相關函數語法: 1. ind = find(X) 2. ind = find(X, k) 3. ind = find(X, k, 'first') 4. ind = find(X, k, 'last') 5. [row,col] = find(X, ...) ...
  • 一、A為3行4列的矩陣,B為一個行數大於3的矩陣,寫出MATLAB命令。 (1)刪除A的第1、3兩列。 (2)刪除B的倒數第3行。 (1)刪除A的第1、3列 ​A=rand(3,4) ​A(:,[1,3])=[] 輸出: A = 0.9572 0.1419 0.7922 0.0357 0.4854 ...
  • python3-cookbook中每個小節以問題、解決方案和討論三個部分探討了Python3在某類問題中的最優解決方式,或者說是探討Python3本身的數據結構、函數、類等特性在某類問題上如何更好地使用。這本書對於加深Python3的理解和提升Python編程能力的都有顯著幫助,特別是對怎麼提高Py ...
  • Dart類Getters和Setter Getters和Setter(也稱為訪問器和更改器)允許程式分別初始化和檢索類欄位的值。 使用get關鍵字定義getter或訪問器。Setter或存取器是使用set關鍵字定義的。 預設的getter/setter與每個類相關聯。 但是,可以通過顯式定義sett ...
  • 手把手教您下載安裝Python的運行環境,本文雖然寫於2020年Python穩定的版本是3.8,Windows流行的版本是Win10,學會方法50年管用,本教程會在電腦上安裝2套Python環境,1-3節安裝原生環境,第4節安裝Visual Studio Code的環境。 ...
一周排行
    -Advertisement-
    Play Games
  • 基於.NET Framework 4.8 開發的深度學習模型部署測試平臺,提供了YOLO框架的主流系列模型,包括YOLOv8~v9,以及其系列下的Det、Seg、Pose、Obb、Cls等應用場景,同時支持圖像與視頻檢測。模型部署引擎使用的是OpenVINO™、TensorRT、ONNX runti... ...
  • 十年沉澱,重啟開發之路 十年前,我沉浸在開發的海洋中,每日與代碼為伍,與演算法共舞。那時的我,滿懷激情,對技術的追求近乎狂熱。然而,隨著歲月的流逝,生活的忙碌逐漸占據了我的大部分時間,讓我無暇顧及技術的沉澱與積累。 十年間,我經歷了職業生涯的起伏和變遷。從初出茅廬的菜鳥到逐漸嶄露頭角的開發者,我見證了 ...
  • C# 是一種簡單、現代、面向對象和類型安全的編程語言。.NET 是由 Microsoft 創建的開發平臺,平臺包含了語言規範、工具、運行,支持開發各種應用,如Web、移動、桌面等。.NET框架有多個實現,如.NET Framework、.NET Core(及後續的.NET 5+版本),以及社區版本M... ...
  • 前言 本文介紹瞭如何使用三菱提供的MX Component插件實現對三菱PLC軟元件數據的讀寫,記錄了使用電腦模擬,模擬PLC,直至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1. PLC開發編程環境GX Works2,GX Works2下載鏈接 https:// ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • 1、jQuery介紹 jQuery是什麼 jQuery是一個快速、簡潔的JavaScript框架,是繼Prototype之後又一個優秀的JavaScript代碼庫(或JavaScript框架)。jQuery設計的宗旨是“write Less,Do More”,即倡導寫更少的代碼,做更多的事情。它封裝 ...
  • 前言 之前的文章把js引擎(aardio封裝庫) 微軟開源的js引擎(ChakraCore))寫好了,這篇文章整點js代碼來測一下bug。測試網站:https://fanyi.youdao.com/index.html#/ 逆向思路 逆向思路可以看有道翻譯js逆向(MD5加密,AES加密)附完整源碼 ...
  • 引言 現代的操作系統(Windows,Linux,Mac OS)等都可以同時打開多個軟體(任務),這些軟體在我們的感知上是同時運行的,例如我們可以一邊瀏覽網頁,一邊聽音樂。而CPU執行代碼同一時間只能執行一條,但即使我們的電腦是單核CPU也可以同時運行多個任務,如下圖所示,這是因為我們的 CPU 的 ...
  • 掌握使用Python進行文本英文統計的基本方法,並瞭解如何進一步優化和擴展這些方法,以應對更複雜的文本分析任務。 ...
  • 背景 Redis多數據源常見的場景: 分區數據處理:當數據量增長時,單個Redis實例可能無法處理所有的數據。通過使用多個Redis數據源,可以將數據分區存儲在不同的實例中,使得數據處理更加高效。 多租戶應用程式:對於多租戶應用程式,每個租戶可以擁有自己的Redis數據源,以確保數據隔離和安全性。 ...