典型用法
基礎用法
@GetMapping("/users/{id}")
public String getUser(@PathVariable Long id) {return "User ID: " + id;
}
請求:/users/1001
輸出:User ID: 1001----
@GetMapping("/users/{userId}/orders/{orderId}")
public String getOrder(@PathVariable("userId") Long userId,@PathVariable("orderId") Long orderId) {return "User: " + userId + ", Order: " + orderId;
}
請求:/users/1001/orders/2002
輸出:User: 1001, Order: 2002
路徑變量與類型轉換
Spring 自動進行類型轉換(如 String → Integer、String → Long 等):
@GetMapping("/products/{id}")
public String getProduct(@PathVariable Integer id) {return "Product ID: " + id;
}
請求:/products/3003
輸出:Product ID: 3003
使用 Map 接收所有路徑變量
當不確定路徑變量名稱或需要動態處理時,可以使用 Map:
@GetMapping("/books/{category}/{bookId}")
public String getBookInfo(@PathVariable Map<String, String> pathVars) {return "Category: " + pathVars.get("category") + ", Book ID: " + pathVars.get("bookId");
}
請求:/books/fiction/978123
輸出:Category: fiction, Book ID: 978123
路徑變量不必須存在
Spring 的 @PathVariable 注解 默認要求路徑變量必須存在,否則會拋出異常(如 NoHandlerFoundException)
@GetMapping("/posts/{id}")
public String getPost(@PathVariable Long id) {return "Post ID: " + id;
}請求 /posts/123 ? 正常
請求 /posts ? 報錯:找不到匹配的路徑
// ?方法一:使用多個路徑映射(推薦)
@GetMapping({"/posts", "/posts/{id}"})
public String getPost(@PathVariable(required = false) Long id) {if (id == null) {return "訪問所有文章列表";}return "訪問文章詳情,ID: " + id;
}
請求 /posts → 輸出:訪問所有文章列表
請求 /posts/123 → 輸出:訪問文章詳情,ID: 123// ?方法二:使用 Optional(Spring 5.0+ 推薦)
@GetMapping({"/posts", "/posts/{id}"})
public String getPost(@PathVariable Optional<Long> id) {return id.map(i -> "訪問文章詳情,ID: " + i).orElse("訪問所有文章列表");
}