PathVariable
时间: 2023-10-14 16:26:00 浏览: 65
PathVariable is an annotation in Spring Boot that is used to extract a parameter from the URL path of a request. It is used to capture dynamic values from the URL and pass them as arguments to a controller method.
For example, consider the following URL:
```
http://example.com/products/123
```
Here, the value "123" is a dynamic parameter that represents the ID of a product. We can use the @PathVariable annotation to extract this value and pass it as an argument to a controller method:
```java
@GetMapping("/products/{id}")
public Product getProductById(@PathVariable Long id) {
// ...
}
```
The @PathVariable annotation maps the value of the "id" parameter in the URL to the "id" parameter in the method signature. Spring automatically converts the String value from the URL to the appropriate data type.
We can also specify a custom name for the path variable using the following syntax:
```java
@GetMapping("/products/{productId}")
public Product getProductById(@PathVariable("productId") Long id) {
// ...
}
```
In this case, the variable name "productId" is used instead of "id".
阅读全文