1.通过 url 来进行传递参数
通过url传参
|---get方式Url传参
|---@PathVariable 即:url/id/1994 形式
|---@RequestParam 即:url?username=zed形式
|---POST方式传参
|---@RequestParam
|---请求体中加入文本
1.1 get方式传递参数 http://localhost:9528/hello/zhangsan
@RestController
public class HelloController {
// 用来映射 get 请求
@GetMapping("/hello/{name}")
public String hello(@PathVariable("name") String name){
System.out.println("获取到的的name值为:" + name);
return "hello" + name;
}
}
1.2 get方式传递参数 http://localhost:9528/hello?name=admin
@RestController
public class HelloController {
// 用来映射 get 请求
@GetMapping("/hello")
public String hello(@RequestParam("name") String name){
System.out.println("获取到的的name值为:" + name);
return "hello" + name;
}
}
给定默认值的参数传递
@RestController
public class HelloController {
// 用来映射 get 请求
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "张三") String name){
System.out.println("获取到的的name值为:" + name);
return "hello" + name;
}
}
参数是不必须的,给@RequestParam(required = false) 表示这个参数可以传也可以不传,不传的话为 null
@RestController
public class HelloController {
// 用来映射 get 请求
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", required = false) String name){
System.out.println("获取到的的name值为:" + name);
return "hello" + name;
}
}
小结:
- 1.defaultValue = "xxx" :使用默认值
- 2.required = false :标注参数是非必须的
1.3 使用 postman 进行发送 post请求 localhost:9528/hello?name=张三&age=22
@RestController
public class HelloController {
// post 传递参数
@PostMapping("/hello")
public String hello(@RequestParam("name") String name, @RequestParam("age") Integer age){
System.out.println(name+"---"+age);
return name+"---"+age;
}
}
同理也可以给接收传递下来的参数进行赋初值操作 设置 required = false
@RestController
public class HelloController {
// post 传递参数
@PostMapping("/hello")
public String hello(@RequestParam(value = "name", required = false) String name, @RequestParam(value = "age", required = false) Integer age){
System.out.println(name+"---"+age);
return name+"---"+age;
}
}