Ambiguous handler methods mapped for '/user/1'

使用rest编程风格时,可以直接将变量值放入到url中,传递到后台,后台自动识别对应的方法,方便很多。

但若出现方法重载的情况,则可能会出问题,如下

@RestController
@RequestMapping("/user")
public class UserController {

	@Resource
	private UserService us;
	
	@ResponseBody
	@GetMapping("/{username}")
	public User getUser(@PathVariable("username")String username) {
		return us.getUser(username);
	}
	
	@ResponseBody
	@GetMapping("/{id}")
	public User getUser(@PathVariable("id")Integer id) {
		return us.findUserById(id);
	}
}

在浏览器地址栏访问 http://localhost:8080/user/1 或 http://localhost:8080/user/lucy 时均会出现如下错误

Ambiguous handler methods mapped for '/user/lucy' ,字面含义,模棱两可的处理方法对于'/user/lucy' ,有两个或以上的方法对于'/user/lucy',这里说明,spring无法根据传参的类型自动匹配处理的方法。

此时,如果依然想使用rest编程风格,则必须改变请求url的格式,必须时url对应的方法不产生歧义

针对上面的例子,可以给变量前面增加参数的类型简写,这样就可以匹配到不同的方法

	@ResponseBody
	@GetMapping("/s/{username}")
	public User getUser(@PathVariable("username")String username) {
		return us.getUser(username);
	}
	
	@ResponseBody
	@GetMapping("/i/{id}")
	public User getUser(@PathVariable("id")Integer id) {
		return us.findUserById(id);
	}

再到浏览器地址栏通过 http://localhost:8080/user/s/lucy 或 http://localhost:8080/user/i/1 来请求

均可以正常访问到后台对象内容

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值