PathVariable获取 URL 路径中的占位符的值把路径上的片段绑定到 Java 方法参数上。是一种REST风格接口简单来讲就是参数放在 URL 斜杠/之间不是?后面。补区分RequestParam取?keyvalue问号后面的查询参数PathVariable取/xxx/123路径里的路径片段示例代码RequestMapping(/request)publicclassRequestController{RequestMapping(/{articleId})publicStringr9(PathVariable(articleId)IntegerarticleId){return接收到参数:articleId;}}拼接完整访问路径类注解路径 方法注解路径/request /{articleId} → 最终 URL 模板/request/{articleId}注意一定不能是request/r9/{articleId}{articleId}是占位符不是字面字符串访问的时候这里替换成真实数字。eg:真实请求示例http://127.0.0.1:8080/request/66这里路径片段66就对应占位符{articleId}。执行流程1.浏览器 / Postman 发送请求GET /request/662.SpringMVC 拦截请求扫描所有 Controller 的RequestMapping匹配类上RequestMapping(“/request”)接着匹配方法上RequestMapping(“/{articleId}”){articleId}匹配 URL 路径第二段内容663.看到方法参数 PathVariable(“articleId”) Integer articleId“articleId”告诉 Spring去找名字叫articleId的占位符把路径捕获到字符串66自动转换成Integer整数赋值给方法局部变量 articleId4.执行方法返回字符串 接收到参数:66返回给 Postman。结果展示传递两个参数的情况RequestMapping(/{type}/{articleId})publicStringr10(PathVariable(articleId)IntegerarticleId,PathVariableStringtype){return接受到参数: articleId, type:type;}这里定义了两个路径占位符{type} 和 {articleId}两个占位符用斜杠 /隔开代表 URL 路径上连续两段都是参数。类上有前缀 RequestMapping(“/request”)完整访问模板/request/{type}/{articleId}正确访问示例请求地址GET http://127.0.0.1:8080/request/news/101news → 匹配占位符 {type}101 → 匹配占位符 {articleId}参数注解拆解PathVariable(articleId)IntegerarticleId,PathVariableStringtypePathVariable(“articleId”) Integer articleId从路径拿到 {articleId} 的值转为 Integer赋值给变量articleId。这里指定了名字 “articleId”和占位符对应。PathVariable String type这里省略了名字要求方法参数名 type 和占位符名字 {type} 完全一致。不一致会报500的错误Java8 才支持省略名称完整写法PathVariable(“type”) String type。执行流程以请求/request/news/101 为例1.Spring 匹配类前缀/request2.匹配方法路径模板/{type}/{articleId}路径片段news捕获给占位符{type}路径片段101捕获给占位符{articleId}3.PathVariable把捕获到字符串拿出来自动做类型转换Spring 从 URL 路径拿到的永远是字符串再帮你自动转成你写的参数类型Integer、Double等不用自己写代码做Integer.parseInt()。“news” → String type“101” → Integer articleId4.执行方法拼接字符串返回给 Postman。