SpringMVC的URL组成,以及URI中对/斜杠的处理,解决IllegalStateException: Ambiguous mapping

SpringMVC的URL组成

ip + 端口号 + 上下文 + 类上的@RequestMapping的URI + 方法上的@RequestMapping的URI

规则

  • 非空URI前会自动拼接/
  • 连续的斜杠会被替换成单个斜杠
  • 方法的URI前没有斜杠与只有一个斜杠的两种接口,同时存在时,拼接前面的斜杠后再替换重复斜杠,得到的结果相同,无法确定最终映射接口,有歧义,启动报错java.lang.IllegalStateException: Ambiguous mapping
  • 配置server.servlet.context-path上下文时,需手动添加前置斜杠,如 server.servlet.context-path=/my-context

演示代码

java 复制代码
package com.example.controllerdemo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
// 类上的@RequestMapping的URI,前面是否有斜杠的结果相同,后面是否有斜杠会影响 @GetMapping() 不指定URI的请求地址
//@RequestMapping("easy")
//@RequestMapping("/easy")
@RequestMapping("easy/")
//@RequestMapping("/easy/")
//@RequestMapping("easy")
public class TestController {

    @GetMapping()
    public String test() {
        return "no";
    }

    // 请求地址 http://localhost:8080/my-context/easy/test
    @GetMapping("test")
    public String test1() {
        return "test";
    }

    // 前面没有斜杠或者只有一个斜杠,结果是相同的,两种接口同时存在时有歧义
    // 启动时无法确定用哪个,报错java.lang.IllegalStateException: Ambiguous mapping

    // 请求地址 http://localhost:8080/my-context/test,与 @GetMapping("test") 相同
//    @GetMapping("/test")
//    public String test2() {
//        return "/test";
//    }

    // 请求地址 http://localhost:8080/my-context/easy/test/
    @GetMapping("test/")
    public String test3() {
        return "test/";
    }
    
//    @GetMapping("/test/")
//    public String test31() {
//        return "/test/";
//    }

    // 方法前的多个连续的斜杠会被处理成单个斜杠,虽然不会因为Ambiguous mapping启动报错,但无法被访问
    // 发送 http://localhost:8080/my-context/easy//test 请求会按照 http://localhost:8080/my-context/easy/test 处理
    @GetMapping("//test")
    public String test21() {
        return "//test";
    }

}
相关推荐
callJJ1 小时前
Spring Data Redis 两种编程模型详解:同步 vs 响应式
java·spring boot·redis·python·spring
wbs_scy2 小时前
Linux线程同步与互斥(三):线程同步深度解析之POSIX 信号量与环形队列生产者消费者模型,从原理到源码彻底吃透
java·开发语言
jinanwuhuaguo3 小时前
(第三十三篇)五月的文明奠基:OpenClaw 2026.5.2版本的文明级解读
android·java·开发语言·人工智能·github·拓扑学·openclaw
xmjd msup4 小时前
spring security 超详细使用教程(接入springboot、前后端分离)
java·spring boot·spring
952364 小时前
SpringBoot统一功能处理
java·spring boot·后端
Lyyaoo.4 小时前
优惠券秒杀业务分析
java·开发语言
消失的旧时光-19434 小时前
统一并发模型:线程、Reactor、协程本质是一件事(从线程到协程 · 第6篇·终章)
java·python·算法
勿忘初心12214 小时前
Java 国密 SM4 加密工具类实战(Hutool + BouncyCastle)|企业级数据加密 + 兼容 JDK8
java·数据安全·数据加密·后端开发·企业级开发·国密 sm4
庞轩px4 小时前
第8篇:原子类与CAS底层原理——无锁并发的实现
java·cas·乐观锁·aba·无锁编程·自旋
rleS IONS5 小时前
SpringBoot中自定义Starter
java·spring boot·后端