SpringBoot中Controller接收参数的几种方式

本文介绍了SpringBoot在Controller中处理请求参数的多种方式,包括@PathVariable用于获取路径参数,@RequestParam用于获取查询参数,@RequestBody用于接收JSON格式的Body参数,以及如何通过@RequestHeader和@CookieValue获取请求头和Cookie值。

第一类:请求路径参数

1、@PathVariable

@GetMapping("getcitylist/{id}")
public List<Classify> getCityList(@PathVariable("id") Long id) {

获取路径参数。即url/{id}这种形式。

2、@RequestParam

@GetMapping("ceshi")
public List<Long> getCityList(@RequestParam("name") String name) {

获取查询参数。即url?name=这种形式

第二类:Body参数
3、@RequestBody
在这里插入图片描述 传入Json时,请求方式不能用Get请求

@PostMapping("/getCustomerList")
	public JsonObject getCustomerList(@RequestBody Customer customer){

Customer为项目中的POJO类,用于接收对象

也可以这样

@PostMapping(path = "/demo1")
public void demo1(@RequestBody Map<String, String> person) {

使用Map接收时不需要POJO类

第三类:请求头参数以及Cookie

1、@RequestHeader
2、@CookieValue

@GetMapping("/demo3")
public void demo3(@RequestHeader(name = "myHeader") String myHeader,
        @CookieValue(name = "myCookie") String myCookie) {
    System.out.println("myHeader=" + myHeader);
    System.out.println("myCookie=" + myCookie);
}

也可以这样

@GetMapping("/demo3")
public void demo3(HttpServletRequest request) {
    System.out.println(request.getHeader("myHeader"));
    for (Cookie cookie : request.getCookies()) {
        if ("myCookie".equals(cookie.getName())) {
            System.out.println(cookie.getValue());
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值