当前位置:   article > 正文

Spring Boot 接口统一前缀 path-prefix_springboot配置请求前缀

springboot配置请求前缀

需求

需求如题,想给一个 spring boot 项目的所有请求路径添加统一前缀,可以通过 context-path 来配置。但是在同时存在静态资源和 Controller 接口的项目中,如果希望静态资源从根路径访问,并且所有接口拥有统一路径前缀,则需要通过 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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

如上URL示例中,希望放在 springboot 根目录 static 中的静态资源能直接通过根路径访问。其他 Controller 接口的前缀 “/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));
    }
    
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

2、application.properties

spring.controller.path-prefix=/api
  • 1

配置文件中参数 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";
    }
    
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

最后将 dog.png 放在 springboot 项目的 static 目录中用来测试。

验证

打开浏览器分别访问如下路径可以正常显示结果,表示成功。

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


(END)

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号