SpringBoot實現(xiàn)接口統(tǒng)一前綴
需求
需求如題,想給一個 spring boot 項目的所有請求路徑添加統(tǒng)一前綴,可以通過 context-path 來配置。但是在同時存在靜態(tài)資源和 Controller 接口的項目中,如果希望靜態(tài)資源從根路徑訪問,并且所有接口擁有統(tǒng)一路徑前綴,則需要通過 Spring 層面來解決這個問題(context-path 是 web 容器層面的,如果配置它則會把靜態(tài)資源都包含進(jìn)去)。
如下接口示例:
# 3個靜態(tài)資源
http://localhost:8080/index.html
http://localhost:8080/home.js
http://localhost:8080/dog.png
# 3個統(tǒng)一前綴為 /api
http://localhost:8080/api/test/show
http://localhost:8080/api/test/display
http://localhost:8080/api/test/print
如上URL示例中,希望放在 springboot 根目錄 static 中的靜態(tài)資源能直接通過根路徑訪問。其他 Controller 接口的前綴 “/api” 可以在配置文件中自定義配置變更。
實現(xiàn)
實現(xiàn)方法很簡單,如下代碼和配置文件:
1、GlobalControllerPathPrefixConfiguration.java
package com.example.demospringbean; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** ?* 為 Controller 接口配置統(tǒng)一前綴 ?* ?* @author shanhy ?* @date 2023-03-20 15:50 ?*/ @Configuration public class GlobalControllerPathPrefixConfiguration implements WebMvcConfigurer { ? ? @Value("${spring.controller.path-prefix:}") ? ? private String pathPrefix; ? ? @Override ? ? public void configurePathMatch(PathMatchConfigurer configurer) { ? ? ? ? configurer.addPathPrefix(pathPrefix, c -> c.isAnnotationPresent(RestController.class)); ? ? } }
2、application.properties
spring.controller.path-prefix=/api
配置文件中參數(shù) spring.controller.path-prefix 也可以是多級路徑,例如 /api/demo。
3、TestController.java
/** * 接口示例 * * @author shanhy * @date 2023-03-20 15:49 */ @RestController @RequestMapping("/test") public class TestController { @GetMapping("/show") public String show(){ return "OK"; } }
最后將 dog.png 放在 springboot 項目的 static 目錄中用來測試。
驗證
打開瀏覽器分別訪問如下路徑可以正常顯示結(jié)果,表示成功。
http://localhost:8080/dog.png
http://localhost:8080/api/test/show
到此這篇關(guān)于SpringBoot實現(xiàn)接口統(tǒng)一前綴的文章就介紹到這了,更多相關(guān)SpringBoot 接口統(tǒng)一前綴內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot統(tǒng)一接口返回及全局異常處理高級用法
- Spring?Boot的幾種統(tǒng)一處理方式梳理小結(jié)
- SpringBoot返回結(jié)果統(tǒng)一處理實例詳解
- Springboot中@Async異步,實現(xiàn)異步結(jié)果合并統(tǒng)一返回方式
- SpringBoot統(tǒng)一返回處理出現(xiàn)cannot?be?cast?to?java.lang.String異常解決
- SpringBoot使用AOP實現(xiàn)統(tǒng)一角色權(quán)限校驗
- Spring?Boot項目完美大一統(tǒng)(結(jié)果異常日志統(tǒng)一)
相關(guān)文章
Java基礎(chǔ)學(xué)習(xí)之字符緩沖流的應(yīng)用
這篇文章主要為大家詳細(xì)介紹了Java基礎(chǔ)中的字符緩沖流的相關(guān)應(yīng)用,例如復(fù)制Java文件等,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一2022-09-09Java請求調(diào)用參數(shù)格式為form-data類型的接口代碼示例
這篇文章主要給大家介紹了關(guān)于Java請求調(diào)用參數(shù)格式為form-data類型的接口的相關(guān)資料,文中給出了詳細(xì)的代碼示例,對大家的學(xué)習(xí)或者工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08jmeter實現(xiàn)接口關(guān)聯(lián)的兩種方式(正則表達(dá)式提取器和json提取器)
Jmeter用于接口測試時,后一個接口經(jīng)常需要用到前一次接口返回的結(jié)果,本文主要介紹了jmeter實現(xiàn)接口關(guān)聯(lián)的兩種方式,感興趣的小伙伴們可以參考一下2021-11-11