方法 1:URL 查詢參數(Query Parameters)
格式:?參數名=值&參數名2=值2
示例請求
http://localhost:8080/hello?name=張三&age=25
后端接收方式
@GetMapping("/hello") public String sayHello(@RequestParam String name,@RequestParam(required = false, defaultValue = "18") Integer age ) {return "你好 " + name + ",年齡:" + age; }
關鍵點:
@RequestParam
?默認要求參數必須存在使用?
required = false
?可讓參數變為可選defaultValue
?設置默認值
方法 2:路徑參數(Path Variables)
格式:/路徑/{參數}
示例請求
http://localhost:8080/hello/張三
后端接收方式
@GetMapping("/hello/{name}") public String sayHello(@PathVariable String name) {return "你好 " + name; }
適用場景:
參數是URL的一部分時(如RESTful資源ID)
需要更簡潔的URL結構時