簡體   English   中英

使用不同路徑訪問 REST API 中的相同資源

[英]To use different paths to access same resource in REST API

使用 Spring-boot:MVC, REST API

背景:Model=Student >> Long age(Student類的屬性之一)

我可以定義兩個 URL 路徑來訪問特定學生的年齡嗎? 例子:

  1. 通過學生ID訪問

`

@GetMapping("/{id}/age")
public ResponseEntity<String> getStudentAge(@PathVariable Long id) {
    String age = studentService.retrieveAgeById(id);
    return new ResponseEntity<String>(age, HttpStatus.OK);
}

`

SQL 查詢(使用 id ):

@Query("select d.id, d.age from Student d where d.id=:id")
String findAgeById(Long id);
  1. 按學生姓名訪問年齡

`

   @GetMapping("/{name}/age")
        public ResponseEntity<String>  getStudentAgeByName(@PathVariable String name) {
            String age = studentService.retrieveAgeByName(name);
            return new ResponseEntity<String>(age, HttpStatus.OK);
        }

`

SQL 查詢(使用名稱):

@Query("select d.name, d.age from Student d where d.name=:name")
    String findAgeByName(String name);

此方法產生此錯誤:

出現意外錯誤(類型=內部服務器錯誤,狀態=500)。 Ambiguous handler methods mapped for '/2/age': {public org.springframework.http.ResponseEntity com.example.restapi.controller.StudentController.getStudentAgeByName(java.lang.String), public org.springframework.http.ResponseEntity com. example.restapi.controller.StudentController.getStudentAge(java.lang.Long)}

因為/{name}/age/{id}/age是相同的路徑。 這里, {name}{id}是路徑變量。

因此,您正在嘗試使用相同的路徑執行 map 兩種不同的處理程序方法。 這就是為什么 spring 給你錯誤Ambiguous handler methods mapped

您可以嘗試這種方式來解決這個問題

@GetMapping("/age/{id}")
public ResponseEntity<String> getStudentAge(@PathVariable Long id) {
    String age = studentService.retrieveAgeById(id);
    return new ResponseEntity<String>(age, HttpStatus.OK);
}

@GetMapping("/age/name/{name}")
public ResponseEntity<String>  getStudentAgeByName(@PathVariable String name) {
     String age = studentService.retrieveAgeByName(name);
     return new ResponseEntity<String>(age, HttpStatus.OK);
}

但最好將請求參數用於name等非標識符字段

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM