09. Spring Boot Controller 接受参数的几种常用方式

1. 接受参数的几种常用方式
  1. 请求路径参数

    1. @PathVariable

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

      // 访问路径:http://localhost:8080/hello/5
      @RequestMapping(value = "hello/{id}", method = RequestMethod.GET)
      public JsonResult hello(@PathVariable Integer id) {
          return JsonResult.success(null);
      }
      
    2. @RequestParam

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

      // 访问路径:http://localhost:8080/hello/hello?id=5
      @RequestMapping(value = "/hello", method = RequestMethod.GET)
      public JsonResult hello(@RequestParam("id") Integer id)  {
          return JsonResult.success(null);
      }
      

      如果传入的参数为空,可以设置为默认的

      // 访问路径:http://localhost:8080/hello/hello?id=5
      @RequestMapping(value = "/hello", method = RequestMethod.GET)
      public JsonResult hello(@RequestParam(value = "id", required = false, defaultValue = 5) Integer id)  {
          return JsonResult.success(null);
      }
      
  2. Body参数@RequestBody

    @RequestMapping(value = "/hello", method = RequestMethod.POST)
    public JsonResult hello(@RequestBody Person person) {
        return JsonResult.success(null);
    }
    
  3. 请求头参数以及Cookie@RequestHeader@CookieValue

    @RequestMapping(value = "/hello", method = RequestMethod.POST)
    public JsonResult hello(@RequestHeader(name = "myHeader") String myHeader, @CookieValue(name = "myCookie") String myCookie) {
        return JsonResult.success(null);
    }
    
2. 示例
  1. 获取当前登录人账号

    @RequestMapping(value = "/hello", method = RequestMethod.POST)
    public JsonResult hello(@RequestHeader(name = "loginUserId") String loginUserId){
        return JsonResult.success(null);
    }
    
  2. 获取request和response

    @RequestMapping(value = "/hello", method = RequestMethod.POST)
    public JsonResult hello(HttpServletRequest request, HttpServletResponse response){
        return JsonResult.success(null);
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值