gpt4 book ai didi

java - Spring GET相同的URL但不同的参数类型

转载 作者:行者123 更新时间:2023-12-01 10:05:19 24 4
gpt4 key购买 nike

所以我正在创建一个用户 API,并尝试在登录之前调用 getUserByEmail() 。我的问题是我得到了一个映射为 HTTP 路径错误的模糊处理程序方法。

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> getUser(@PathVariable("id") int id) {
System.out.println("Fetching User with id " + id);
User user = userService.findById(id);
if (user == null) {
System.out.println("User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<User>(user, HttpStatus.OK);
}

@RequestMapping(value = "/user/{email}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> getUserByEmail(@PathVariable("email") String email) {
System.out.println("Fetching User with email " + email);
User user = userService.findByEmail(email);
if (user == null) {
System.out.println("User with email " + email + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<User>(user, HttpStatus.OK);
}

这是我得到的错误响应:

{"timestamp":1460226184275,"status":500,"error":"内部服务器错误","exception":"java.lang.IllegalStateException","message":"映射到 HTTP 路径的不明确处理程序方法' http://localhost:8080/user/fr ': {public org .springframework.http.ResponseEntity com.ffa.controllers.UserController.getUser(int), public org.springframework.http.ResponseEntity com.ffa.controllers.UserController.getUserByEmail(java.lang.String)}","路径":"/用户/fr"}

我知道我的问题与我有一个相同但参数类型不同的 GET 有关。任何帮助将不胜感激!

最佳答案

您可以使用带有两个不同 URL 的 RequestParams,而不是 PathVariables。

@RequestMapping(value = "/user", params="userID", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> getUser(@RequestParam("userID") int id) {
System.out.println("Fetching User with id " + id);
User user = userService.findById(id);
if (user == null) {
System.out.println("User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<User>(user, HttpStatus.OK);
}

@RequestMapping(value = "/user", params="emailID, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE")
public ResponseEntity<User> getUserByEmail(@RequestParam("emailID") String email) {
System.out.println("Fetching User with email " + email);
User user = userService.findByEmail(email);
if (user == null) {
System.out.println("User with email " + email + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<User>(user, HttpStatus.OK);
}

当您调用 /user?userID=123 时,它将调用第一个,当您调用 /user?emailID=something@gamil.com 时,它将调用第一个第二个。这是由 @RequestMapping 中传递的 params 属性负责的。

关于java - Spring GET相同的URL但不同的参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36520964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com