@PathVariable
时间: 2023-05-24 19:05:31 浏览: 98
@PathVariable is a Spring annotation used to extract values from the path of a URL. It can be applied to a method parameter in a Spring MVC controller and used to bind a variable value in a URI template to the parameter.
For example, if we have a REST API endpoint called /books/{id} where {id} represents the unique identifier of a book, we can use @PathVariable to extract the value of the {id} placeholder and retrieve data for the specified book.
Here's an example of how we can use @PathVariable in a Spring MVC controller method:
```
@GetMapping("/books/{id}")
public ResponseEntity<Book> getBookById(@PathVariable Long id) {
Book book = bookService.getBookById(id);
return ResponseEntity.ok(book);
}
```
In this example, @PathVariable is used to extract the value of the {id} variable from the path of the URL and bind it to the id parameter of the getBookById() method. The method then uses the id to retrieve the corresponding book from the database and return it in the response.
阅读全文