必要
要件は前述したとおりですが、Spring Boot プロジェクトのすべてのリクエスト パスに統一プレフィックスを追加したい場合は、context-path を通じて設定できます。ただし、静的リソースとコントローラー インターフェイスの両方が存在するプロジェクトで、ルート パスから静的リソースにアクセスし、すべてのインターフェイスに統一されたパス プレフィックスを持たせたい場合は、Spring レベル (context-path) を通じてこの問題を解決する必要があります。 Web コンテナー レベルです (構成にすべての静的リソースが含まれる場合)。
次のインターフェイスの例:
# 3个静态资源
http://localhost:8080/index.html
http://localhost:8080/home.js
http://localhost:8080/dog.png
# 3个统一前缀为 /api
http://localhost:8080/api/test/show
http://localhost:8080/api/test/display
http://localhost:8080/api/test/print
上記の URL の例では、springboot ルート ディレクトリ static に配置された静的リソースに、ルート パスを介して直接アクセスできることが期待されます。他のコントローラー インターフェイスのプレフィックス「/api」は、構成ファイル内の構成変更に合わせてカスタマイズできます。
成し遂げる
実装方法は非常に簡単で、次のコードと設定ファイルのようになります。
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 接口配置统一前缀
*
* @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、アプリケーションのプロパティ
spring.controller.path-prefix=/api
構成ファイル内のパラメータは
spring.controller.path-prefix
、たとえば、 のようなマルチレベルのパスにすることもできます/api/demo
。
3、テストコントローラー.java
/**
* 接口示例
*
* @author shanhy
* @date 2023-03-20 15:49
*/
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/show")
public String show(){
return "OK";
}
}
最後に、テストのために springboot プロジェクトの静的ディレクトリに Dog.png を配置します。
確認する
ブラウザを開き、以下のパスにそれぞれアクセスすると、正常に結果が表示され、成功しました。
http://localhost:8080/dog.png
http://localhost:8080/api/test/show
(終わり)