@RequestParam vs @PathVariable

@RequestParam vs @PathVariable

技术背景

在Java的Spring框架中,@RequestParam@PathVariable是两个常用的注解,用于从HTTP请求中获取参数。理解它们的区别和使用场景,对于开发高效、清晰的Spring应用至关重要。

实现步骤

@RequestParam

@RequestParam 用于从请求的查询参数中获取值。查询参数通常是URL中问号(?)后面的键值对。

示例URL:http://localhost:8080/springmvc/hello/101?param1=10&param2=20

示例代码:

1
2
3
4
5
6
public String getDetails(
@RequestParam(value="param1", required=true) String param1,
@RequestParam(value="param2", required=false) String param2){
// 处理逻辑
return "result";
}

@PathVariable

@PathVariable 用于从请求的URI模板中获取动态值。URI模板中的占位符使用大括号({})表示。

示例URL:http://localhost:8080/springmvc/hello/101

示例代码:

1
2
3
4
5
6
7
@RequestMapping("/hello/{id}")
public String getDetails(@PathVariable(value="id") String id,
@RequestParam(value="param1", required=true) String param1,
@RequestParam(value="param2", required=false) String param2){
// 处理逻辑
return "result";
}

核心代码

完整示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class ExampleController {

@GetMapping("/group/test")
public String testWithRequestParam(@RequestParam Long id) {
return "Received id: " + id + " from @RequestParam";
}

@GetMapping("/group/test/{id}")
public String testWithPathVariable(@PathVariable Long id) {
return "Received id: " + id + " from @PathVariable";
}
}

最佳实践

  • 使用场景选择
    • 如果参数是与业务逻辑相关的查询条件,如过滤、排序等,使用 @RequestParam
    • 如果参数是URL的一部分,用于标识资源的唯一标识,如用户ID、文章ID等,使用 @PathVariable
  • 参数设置
    • 使用 required 属性明确参数是否必须。
    • 使用 defaultValue 属性为可选参数设置默认值。

常见问题

特殊字符处理

在处理特殊字符时,@RequestParam@PathVariable 有不同的表现。例如,+ 符号在 @RequestParam 中会被视为空格,而在 @PathVariable 中会被视为 + 本身。

参数缺失

默认情况下,@PathVariable 是必需的,如果对应的路径段缺失,Spring会返回404 Not Found错误。而 @RequestParam 可以通过设置 required = false 来使其变为可选参数。如果未提供参数且未设置默认值,方法参数将为 null