需求

需求如题,想给一个 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

如上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));
    }
    
}

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";
    }
    
}

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

验证

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

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


(END)

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐