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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM