Spring Boot 인터페이스 통합 접두사 경로 접두사

필요

요구사항은 앞서 언급한 바와 같으며, 스프링 부트 프로젝트의 모든 요청 경로에 통합 접두사를 추가하려면 context-path를 통해 구성하면 됩니다. 그러나 정적 리소스와 Controller 인터페이스가 모두 존재하는 프로젝트에서 루트 경로에서 정적 리소스에 액세스하고 모든 인터페이스에 통합 경로 접두사가 있는 경우 Spring 레벨(context-path)을 통해 이 문제를 해결해야 합니다. 웹 컨테이너 수준에 있습니다(구성하는 경우 모든 정적 리소스가 포함됩니다).

다음 인터페이스 예:

# 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、application.properties

spring.controller.path-prefix=/api

구성 파일의 매개변수는 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";
    }
    
}

마지막으로 테스트를 위해 springboot 프로젝트의 정적 디렉터리에 dog.png를 배치합니다.

확인하다

브라우저를 열고 각각 다음 경로에 접속하면 정상적으로 결과가 표시되어 성공을 나타냅니다.

http://localhost:8080/dog.png
http://localhost:8080/api/test/show


(끝)

추천

출처blog.csdn.net/catoop/article/details/129669656