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

}
相关推荐
毕设源码-郭学长35 分钟前
【开题答辩全过程】以 高校教材大管家系统为例,包含答辩的问题和答案
java·spring boot
Gavin在路上42 分钟前
DDD之用事件风暴重构“电商订单履约”(11)
java·前端·重构
AnAnCode1 小时前
ECS 架构 (Entity Component System) - 数据导向编程快速入门
java·架构·游戏服务器
qq_12498707531 小时前
基于SpringBoot+vue的小黄蜂外卖平台(源码+论文+部署+安装)
java·开发语言·vue.js·spring boot·后端·mysql·毕业设计
小二·1 小时前
Spring框架入门:TX 声明式事务详解
java·数据库·spring
i02081 小时前
Java 17 + Spring Boot 3.2.5 使用 Redis 实现“生产者–消费者”任务队列
java·spring boot·redis
烤麻辣烫1 小时前
黑马程序员苍穹外卖后端概览
xml·java·数据库·spring·intellij-idea
蓑衣夜行1 小时前
Qt QWebEngine 开启硬件加速注意事项
开发语言·c++·qt·web·qwebengine
天天摸鱼的java工程师2 小时前
JDK 25 到底更新了什么?这篇全景式解读带你全面掌握
java·后端
毕设源码-邱学长2 小时前
【开题答辩全过程】以 个人博客网站为例,包含答辩的问题和答案
java