いくつかのコメントのためにREST APIがあります。現在、最も興味深いのURIは以下のとおりです。Spring RESTはネストされたrequstmappingを再利用します
GET /products/1/comments // get all comments of product 1
GET /products/1/comments/5 // get the 5th comment of product 1
GET /products/1/comments/5/user // get the user of the 5th comment
GET /products/1/comments/latest // get the latest comment of product 1
GET /products/1/comments/latest/user // get the user of the latest comment
加えて、あなたが直接ので
GET /comments/987 // get the comment with id 987
GET /comments/987/user // get the user of comment with id 987
コメントにアクセスすることができ、我々は2 @RestController
を持っている:
@RestController
@RequestMapping("/products/{productId}")
public class ProductsCommentsResource {
@GetMapping(value = "/comments")
public ResponseEntity<?> getComments(@PathVariable Long productId){
// get all products...
}
@GetMapping(value = "/comments/{commentNr}")
public ResponseEntity<?> getComment(@PathVariable Long productId, @PathVaraible Long commentNr){
// get comment with number commentNr of product productId
}
@GetMapping(value = "/comments/{commentNr}/user")
public ResponseEntity<?> getCommentUser(@PathVariable Long productId, @PathVaraible Long commentNr){
// get the user of comment with commentNr of productId
}
@GetMapping(value = "/comments/latest")
public ResponseEntity<?> getLatestComment(@PathVariable Long productId){
// get latest commentNr and call getComment(productId, commentNr)
}
@GetMapping(value = "/comments/latest/user")
public ResponseEntity<?> getLatestCommentUser(@PathVariable Long productId){
// get latest commentNr and call getCommentUser(productId, commentNr)
}
}
@RestController
@RequestMapping("/comments")
public class CommentsResource {
@GetMapping(value = "/{commentId}")
public ResponseEntity<?> getComment(@PathVaraible Long commentId){
// get comment id commentId
}
@GetMapping(value = "/{commentId}/user")
public ResponseEntity<?> getCommentUser(@PathVaraible Long commendId){
// get the user of comment with id commentId
}
}
latest
そのためだけです"最後のcommentNrを取得し、このcommentIdを使用して対応するメソッドを呼び出す"のreplacement-keyword "
これは単なる抜粋であり、ユーザーに加えて、コメントには約30のサブリソースとサブサブリソース(POST、DELETEなどのメソッドを含む)があります。 したがって、私たちは多かれ少なかれ3回すべてを持っています。
重複したコードなどを削除するには、これを改善する必要があります。 コメントリソースを「カプセル化」し、クラスに注釈付きの@RequestMapping
を使用して再利用できるようにすることです。
/products/1/comments/latest/user
と製品1の「最新」 コールがにリダイレクトされます
- に
/products/1/comments/latest[what ever]
- `` `/コメント/ {} commendId
したがって/ユーザー、我々は をリダイレクトする何かを持っている必要があります ~/products/1/comments/5[what ever]
~/comments/{commentId}[what ever]
であり、/ comments/{commentId}は唯一の実装である。
しかし、私たちは春のドキュメントでは、適切なものを見つけられませんでした...
を使用すると簡単に解決できます。常にパスの商品はオプションではないと考えました。私は試してみます – Indivon