You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot如何禁止@RequestMapping等映射注解自动追加末尾斜杠

问题原因

该现象来自Spring MVC的默认路径拼接规则,不属于Spring Boot的额外处理逻辑:
Spring MVC在处理控制器类上@RequestMapping与方法上@XMapping注解的路径时,默认会自动在两段路径中间插入斜杠(/)作为路径分隔符,避免出现路径拼接错误。你当前类上配置的前缀路径为/@,方法上配置的路径为{name},默认拼接后生成的最终路径就是/@/{name},因此无法匹配你预期的/@{name}格式路径。

禁用自动追加斜杠的实现方案

无需修改现有接口注解,无需新增过滤器,也不需要调整Tomcat相关配置,仅需新增一个Spring MVC配置类,调整路径匹配规则即可:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UrlPathHelper;

@Configuration
public class MvcPathConfig implements WebMvcConfigurer {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper pathHelper = new UrlPathHelper();
        // 启用全路径匹配,禁止框架自动拼接类与方法路径时补插斜杠
        pathHelper.setAlwaysUseFullPath(true);
        configurer.setUrlPathHelper(pathHelper);
        // Spring Boot 2.6及以上版本默认使用PathPatternParser,需切回AntPathMatcher支持该场景
        configurer.setPatternParser(null);
    }
}

配置完成后重启项目,即可直接通过/@user1这类格式的路径访问接口,@PathVariable可以正常获取到name参数的值。

内容的提问来源于stack exchange,提问作者user15049586

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 17:27:02