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

}
相关推荐
蜡台几秒前
Android Gradle 项目下载编译失败解决---持续更新
android·java·kotlin·gradle
迈巴赫车主1 分钟前
天梯赛 L2-004 这是二叉搜索树吗?java
java·开发语言·数据结构·算法·天梯赛
z止于至善10 分钟前
服务器发送事件(SSE):前端实时通信的轻量解决方案
前端·web·服务器通信
JMchen12331 分钟前
跨技术栈:在Flutter/Compose中应用自定义View思想
java·经验分享·flutter·canvas·dart·自定义view
黄昏晓x32 分钟前
C++11
android·java·c++
Java水解40 分钟前
RUST异步并发安全与内存管理的最佳实践
java·后端·面试
李白的粉42 分钟前
基于springboot的论坛网站
java·spring boot·毕业设计·课程设计·论坛网站
Hvitur1 小时前
eclipse新建SpringBoot项目
java·spring boot·eclipse
Nandeska1 小时前
6、认识和使用Redis Stack
java·数据库·redis
J2虾虾1 小时前
Springboot项目中循环依赖的问题
java·开发语言