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

}
相关推荐
_日拱一卒14 分钟前
LeetCode:994腐烂的橘子
java·数据结构·算法·leetcode·深度优先
隔窗听雨眠20 分钟前
Nginx网关响应慢排查手记
java·服务器·nginx
智慧物业老杨44 分钟前
智慧物业合同周期管理系统:从风险预警到智能交接的全流程数智化落地方案
java·人工智能·python
源码宝1 小时前
MES系统源码:Java8 + SpringBoot2.7 + MySQL8 + Redis,后端源码清爽易扩展
java·后端·源码·springboot·mes系统·源码二开·mes源码
JAVA社区1 小时前
Java高级全套教程(十)—— SpringCloudAlibaba超详细实战详解
java·开发语言·spring cloud·面试·职场和发展
金銀銅鐵2 小时前
[Java] 如何理解 class 文件中方法的 descriptor?
java·后端
云烟成雨TD2 小时前
Spring AI Alibaba 1.x 系列【63】AI Agent 长期记忆
java·人工智能·spring
憧憬成为java架构高手的小白2 小时前
苍穹外卖--day09
java·spring boot·百度
学代码的真由酱2 小时前
Java多用户一对一网页聊天室-测试报告
java·开发语言·功能测试·测试
Jasonakeke3 小时前
SpringBoot自动配置原理揭秘
java·spring boot·后端