在本快速教程中,我们将探讨Spring的@RequestParam和@PathVariable批注之间的区别。
@RequestParam和@PathVariable都可以用于从请求URI提取值,但是它们有些不同。
@RequestParam从查询字符串提取值:
@GetMapping("/foos") |
[b]http://localhost:8080/foos?id=abc[/b] |
@PathVariables从URI提取路径值:
@GetMapping("/foos/{id}") |
两者URL不同。因为@PathVariable从URI路径中提取值,所以未对其进行编码。另一方面,@ RequestParam则是对URI编码。
@PathVariable未解码URL参数:
http://localhost:8080/foos/ab+c |
@RequestParam 请求该参数是URL解码的:
http://localhost:8080/foos?id=ab+c |
完整源代码可以在GitHub上找到