Spring获取相同的URL但不同的参数类型

时间:2016-04-09 18:29:36

标签: java spring spring-mvc

所以我正在创建一个用户API,我试图在登录前调用getUserByEmail()。我的问题是我得到一个为HTTP路径ERROR映射的Ambiguous处理程序方法。

@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);
}

以下是我得到的错误回复:

{&#34; timestamp&#34;:1460226184275,&#34; status&#34;:500,&#34; error&#34;:&#34; Internal Server Error&#34;,&#34; exception&#34;:&#34; java.lang.IllegalStateException&#34;,&#34; message&#34;:&#34;为HTTP路径映射的模糊处理程序方法&#39; http://localhost:8080/user/fr&#39 ;:{public org .springframework.http.ResponseEntity com.ffa.controllers.UserController.getUser(int),public org.springframework .http.ResponseEntity com.ffa.controllers.UserController.getUserByEmail(java.lang.String)}&#34;,&#34; path&#34;:&#34; / user / FR&#34;}

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

1 个答案:

答案 0 :(得分:0)

您可以将RequestParams与两个不同的URL一起使用,而不是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属性来处理。