Spring Boot interface unified prefix path-prefix

need

The requirements are as mentioned. If you want to add a unified prefix to all request paths of a spring boot project, you can configure it through context-path. However, in a project where both static resources and Controller interfaces exist, if you want the static resources to be accessed from the root path and all interfaces have a unified path prefix, you need to solve this problem through the Spring level (context-path is at the web container level, if Configuring it will include all static resources).

The following interface example:

# 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

In the above URL example, it is hoped that the static resources placed in the springboot root directory static can be directly accessed through the root path. The prefix "/api" of other Controller interfaces can be customized for configuration changes in the configuration file.

accomplish

The implementation method is very simple, as follows code and configuration file:

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

Parameters in the configuration file spring.controller.path-prefixcan also be multi-level paths, for example /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";
    }
    
}

Finally, place dog.png in the static directory of the springboot project for testing.

verify

Open the browser and access the following paths respectively. The results will be displayed normally, indicating success.

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


(END)

Guess you like

Origin blog.csdn.net/catoop/article/details/129669656