Ambiguous handler methods mapped for '/user/1'

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/magi1201/article/details/85928036

使用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 来请求

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

猜你喜欢

转载自blog.csdn.net/magi1201/article/details/85928036
今日推荐