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

Spring Boot 3 POST请求带尾斜杠的路由处理问题求助

解决Spring Boot中POST请求带/不带尾斜杠的路径匹配问题

方案一:切换回AntPathMatcher并开启尾斜杠匹配

Spring Boot 2.6+默认使用PATH_PATTERN_PARSER作为路径匹配策略,但该策略不再支持自动匹配尾斜杠。可以通过配置切换回旧的ANT_PATH_MATCHER并开启尾斜杠匹配:

在application.yml中添加以下配置:

spring:
  mvc:
    pathmatch:
      matching-strategy: ANT_PATH_MATCHER
      use-trailing-slash-match: true

配置后,Spring MVC会自动将/context/path和/context/path/视为同一个路径,POST请求不会触发302重定向。

方案二:关闭容器的尾斜杠重定向行为

以Tomcat为例,可以通过配置关闭容器对context路径的重定向,避免POST请求被转为GET:

在application.yml中添加:

server:
  tomcat:
    redirect-context-root: false

保持你原有的控制器映射代码不变:

@RestController
@RequestMapping("")
public class MyController {

    @PostMapping({ "", "/" })
    public ResponseEntity<String> handlePostRequest() {
        // Handling POST request logic
        return ResponseEntity.ok("POST request handled");
    }
}

此时,/context/path和/context/path/的POST请求都会被控制器直接处理,不会触发重定向。

方案三:自定义过滤器重写请求路径

如果上述配置方案不适用,可以自定义过滤器拦截POST请求,手动将不带尾斜杠的路径重写为带尾斜杠的版本,保持请求方法不变:

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import org.springframework.stereotype.Component;
import org.springframework.core.env.Environment;

import java.io.IOException;

@Component
public class TrailingSlashFilter implements Filter {

    private final String contextPath;

    public TrailingSlashFilter(Environment env) {
        this.contextPath = env.getProperty("server.servlet.context-path", "");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String requestURI = req.getRequestURI();

        // 仅处理POST请求且路径为不带尾斜杠的context path
        if ("POST".equals(req.getMethod()) && contextPath.equals(requestURI) && !requestURI.endsWith("/")) {
            HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapper(req) {
                @Override
                public String getRequestURI() {
                    return contextPath + "/";
                }

                @Override
                public String getServletPath() {
                    return "/";
                }
            };
            chain.doFilter(wrappedRequest, response);
        } else {
            chain.doFilter(request, response);
        }
    }
}

这个过滤器会在请求到达控制器前重写路径,让控制器能够匹配到对应的映射方法,同时避免容器的重定向。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 12:15:59