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

}
相关推荐
猿java11 分钟前
精通MySQL却不了解OLAP和 OLTP,正常吗?
java·后端·面试
渣哥24 分钟前
面试官:为什么阿里巴巴要重写HashMap?ConcurrentHashMap哪里不够用?
java
喵手26 分钟前
Java中的HashMap:你了解它的工作原理和最佳实践吗?
java·后端·java ee
weixin_4565881530 分钟前
【java面试day16】mysql-覆盖索引
java·mysql·面试
心月狐的流火号32 分钟前
计算机I/O模式演进与 Java NIO 直接内存
java·操作系统
猿究院-赵晨鹤35 分钟前
JVM基础知识总结
java·jvm
代码输入中...43 分钟前
JVM常见面试题及答案
java·jvm·java面试·java面试题·jvm面试题
猿究院--冯磊1 小时前
JVM垃圾收集器
java·jvm·算法
天天摸鱼的java工程师1 小时前
Go 语言未来会取代 Java 吗?
java·后端