java后台@RequestBody和@RequestParam

RequestBody 接收的是请求体里面(body)的数据

RequestParam接收的是key-value里面的参数,所以它会被切割进行处理从而可以是普通元素、数组、集合、对象等接收

get---》@RequestParam(),不能用@RequestBody

post---》@RequestParam() & @RequestBody

@RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的);

在后端的同一个接收方法里,@RequestBody与@RequestParam()可以同时使用,@RequestBody最多只能有一个,而@RequestParam()可以有多个。

即:如果参数时放在请求体中,application/json传入后台的话,那么后台要用@RequestBody才能接收到;
如果不是放在请求体中的话,那么后台接收前台传过来的参数时,要用@RequestParam来接收,或者形参前什么也不写也能接收。

注:如果参数前写了@RequestParam(xxx),那么前端必须有对应的xxx名字才行,如果没有xxx名的话,那么请求会出错,报400。

注:如果参数前不写@RequestParam(xxx)的话,那么就前端可以有,也可以没有对应的xxx名字,如果有xxx名的话,那么就会自动匹配;没有的话,请求也能正确发送。

示例1

@AutoLog(value = "运维工程师-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(OperatStaff operatStaff,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<OperatStaff> queryWrapper = QueryGenerator.initQueryWrapper(operatStaff, req.getParameterMap());
        Page<OperatStaff> page = new Page<OperatStaff>(pageNo, pageSize);
        IPage<OperatStaff> pageList = operatStaffService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

示例2

@AutoLog(value = "运维合约管理-添加")
    @ApiOperation(value="运维合约管理-添加", notes="运维合约管理-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody OperatContract[] operatContracts) {
        for(OperatContract operatContract:operatContracts)
        {
            operatContractService.save(operatContract);
        }

        return Result.ok("添加成功!");
    }

示例3

@AutoLog(value = "运维合约管理-通过id删除")
    @ApiOperation(value="运维合约管理-通过id删除", notes="运维合约管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        operatContractService.removeById(id);
        return Result.ok("删除成功!");
    }

示例4

@PostMapping(value = "/sms")
    public Result<String> sms(@RequestBody JSONObject jsonObject) {
        Result<String> result = new Result<String>();
        String mobile = jsonObject.get("mobile").toString();
        String smsmode=jsonObject.get("smsmode").toString();
        log.info(mobile);    
        Object object = redisUtil.get(mobile);
        if (object != null) {
            result.setMessage("验证码10分钟内,仍然有效!");
            result.setSuccess(false);
            return result;
        }

https://blog.csdn.net/justry_deng/article/details/80972817/

原文地址:https://www.cnblogs.com/tiandi/p/15068325.html