SpringBoot学习(2)参数的传递

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;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值