【问题标题】:How to set different prefix for endpoints and for static content in spring boot?如何在 Spring Boot 中为端点和静态内容设置不同的前缀?
【发布时间】:2021-03-10 08:42:01
【问题描述】:

我想问一下是否可以(以及如何)为 Spring Boot 应用程序中的静态内容和端点设置不同的前缀。我一直在应用程序属性中使用server.servlet.contextPath=/api,但它也为静态内容设置前缀。

我想要实现的是为控制器中的端点添加“/api”前缀,并从“/”根目录提供静态内容。

已编辑 实际上我需要的是能够仅将静态内容设置为“/”,并且应用程序的其余部分可以在“/api”上使用

【问题讨论】:

    标签: spring spring-boot spring-mvc controller


    【解决方案1】:

    Spring Boot 为 Web 应用程序使用内置的 WebMvcAutoConfigurationAdapter。默认行为在此类中定义。

    我假设您的控制器带有 @RestController 注释。如果是这种情况,您可以将所有控制器映射到不同的位置。

    创建一个实现WebMvcConfigurer 接口的配置类。覆盖方法configurePathMatch(PathMatchConfigurer configurer) 并实现你想要的路径配置。

    在以下示例中,静态内容仍将在“/”处提供,并且所有 REST 端点都可以使用“/api”作为前缀进行访问。

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.method.HandlerTypePredicate;
    import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {
    
        @Override
        public void configurePathMatch(PathMatchConfigurer configurer) {
            configurer.addPathPrefix("/api", HandlerTypePredicate.forAnnotation(RestController.class));
        }
    
    }
    

    您会注意到此类中没有 @EnableWebMvc 注释,因为它会禁用 WebMvc 的 Spring Boot 自动配置机制。

    【讨论】:

      猜你喜欢
      • 2019-03-24
      • 2018-06-26
      • 2018-03-30
      • 2018-02-10
      • 1970-01-01
      • 2020-08-07
      • 2017-03-25
      • 2017-04-05
      • 1970-01-01
      相关资源
      最近更新 更多